我正在尝试使用React HOC模式以及反向渲染模式来修改组件的子级。到目前为止,这是我在react-jss
HOC中使用injectStyles
的原因。
const styles = {
grid: {
display: "grid",
gridTemplateAreas: ""
},
gridItem: {
display: "inline-flex"
}
};
const GridItemWrapper = ({classes, children}) => (
<div className={classes.gridItem}>{children}</div>
)
const asAGrid = () => (WrappedComponent) => {
const StyledGridItemWrapper = injectStyles(styles)(GridItemWrapper);
class ComponentAsAGrid extends WrappedComponent {
render {
const componentChildren = super.render().props.children;
const {classes, ...rest} = this.props
return cloneElement(<WrappedComponent />, {
className: classes.grid,
...rest,
}, Children.map(componentChildren, child => (
<StyledGridItemWrapper>
{child}
</StyledGridItemWrapper>
)
))
}
}
return injectStyles(styles)(ComponentAsAGrid);
}
我希望这样使用它
class App extends Component {
render() {
return (
<div className={`App ${this.props.className}`}>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default asAGrid()(App);
问题在于,尽管根div
确实具有正确的样式,但子元素并未包装在div
这是问题的沙盒。请注意,如果您检查App
div,它确实应用了正确的样式,但是子级没有div包装器。 https://codesandbox.io/s/ypp74v031v