在javascript库中有一个常见的用例,在这里你想用更高级的组件来装饰你的组件。
例如,material-ui库包含一个样式更高的组件withStyles。
在javascript中,您可以这样做:
import { withStyles } from '@material-ui/core';
const styles = {
example: {
padding: 8
}
}
const SomeComponent = ({classes}) => <div className={classes.example}>I'm a component</div>;
export default withStyles(SomeComponent);如何在Hyperstack中实现同样的目标?
发布于 2019-04-06 06:32:47
首先,看起来有一个issue需要打补丁。这将在下一个版本中得到解决:只需将此方法添加到您的Hypercomponent基类(app/hyperstack/components/hypercomponent.rb)中即可。
def self.to_n
Hyperstack::Internal::Component::ReactWrapper.create_native_react_class(self)
end现在,如果您有以下样式:
MY_STYLES = {root: {backgroundColor: 'red'}}和一个要设置样式的组件:
class StyleTest < HyperComponent
param :some_param
param :classes
render do
DIV(class: classes[:root]) { some_param }
end
end您可以这样做:
class StyledTest1 < HyperComponent
imports `Mui.withStyles(#{MY_STYLES.to_n})(#{StyleTest.to_n})`
end正在发生的事情是,我们放弃了JS,使用反引号,直接调用Mui.with_styles并将其传递给MY_STYLES (就像在MUI文档示例中一样)。to_n将Ruby Hash转换为JS对象。(当将params传递给组件时,这是自动的,但对于简单的函数调用则不是这样。)
然后,我们使用Ruby类(也可以调用to_n来将StyleTest类转换为简单的JS类)调用生成的HOC。
最后,我们将其导入到Hyperstack组件类中。
这比我喜欢的要多一点,所以我们可以只向HyperComponent类添加一个方便的帮助器方法:
class HyperComponent
include Hyperstack::Component
include Hyperstack::State::Observable
param_accessor_style :accessors # this is now the prefered param style
# patch for issue: https://github.com/hyperstack-org/hyperstack/issues/153
def self.to_n
Hyperstack::Internal::Component::ReactWrapper.create_native_react_class(self)
end
# our helper macro:
def self.add_styles(style, opts = {})
imports `Mui.withStyles(#{style.to_n}, #{opts.to_n})(#{superclass.to_n})`
end
end现在我们可以像这样添加样式:
class StyledTest2 < StyleTest
add_styles MY_STYLE
end现在我们有了一个新的组件类,其中包含了我们的风格。
例如:
class App < HyperComponent
render do
DIV do
StyledTest1(some_param: 'test 1')
StyledTest2(some_param: 'test 2')
end
end
endhttps://stackoverflow.com/questions/55539944
复制相似问题