【发布时间】:2016-11-04 04:46:47
【问题描述】:
像这样使用常见的 HOC 模式效果很好。但是,有时您真的不希望组件被包装,而只想扩展您传入的相同组件。这就是我在这里苦苦挣扎的地方。
包装器 HOC
const flexboxContainerStyles = {
display: 'flex',
flexDirection: 'row',
backgroundColor: 'pink',
}
let WrapInFlexContainer = FlexChild => class extends React.Component {
render(){
return (
<div className="flexContainer" style={flexboxContainerStyles} >
<FlexChild {...this.props} />
</div>
)
}
}
const Button = (props) => <button>{props.txt}</button>
let FlexButton = WrapInFlexContainer(Button);
以下示例生成一个没有样式属性的按钮。
示例 1.1:通过 createClass 传递
function hocPassThroughViaClass(Component) {
return React.createClass({
render: function() {
return <Component {...this.props} style={flexboxContainerStyles}/>;
}
});
}
示例 1.2 通过直接渲染传递
let hocPassThroughViaRender = Element => class extends React.Component {
render(){
return <Element {...this.props} className="flexContainer" style={flexboxContainerStyles} />
}
}
示例 2:创建
function hocCreate(Component) {
return React.createClass({
render: function() {
const modifiedProps = Object.assign({}, {...this.props}, {...flexboxContainerStyles});
return React.createElement(Component, { ...modifiedProps });
}
});
}
示例 3:克隆
function hocClone(Component) {
return React.createClass({
render: function() {
const modifiedProps = Object.assign({}, {...this.props}, {...flexboxContainerStyles});
return React.cloneElement(<Component {...modifiedProps } />);
}
});
}
// render examples
let HOCPassThroughViaClassButton = hocPassThroughViaClass(Button); // 1.1
let HOCPassThroughRenderButton = hocPassThroughViaRender(Button); // 1.2
let HOCCreatedButton = hocCreate(Button); // 2
let HOCClonedButton = hocClone(Button); // 3
从我在网络上到处看到的几点来看,如果它是独生子女,似乎不可能返回相同的 Component。
见:https://github.com/threepointone/glamor/blob/master/docs/createElement.md
【问题讨论】:
标签: javascript css reactjs