繁体   English   中英

React HOC 函数不会将 props 传播到 html 元素中

[英]React HOC function does not spread props into html element

我得到了简单的样本。 我想将任何组件传递给一个函数并使用设置背景获取它。 React.createElement组件一起工作正常,但不适用于 html 组件。

 const Title = ({ children }) => { return (<h1 data-this-works="test">{children}</h1>) } const Box = ({ children, ...rest }) => { return React.createElement('span', rest, children) } const styleComponent = BaseComponent => ({children, ...props}) => { const style = {backgroundColor: 'green'} return ( <BaseComponent style={style} {...props} > {children} </BaseComponent> ); } const StyledTitle = styleComponent(Title) const StyledBox = styleComponent(Box) class App extends React.Component { render() { return ( <div> <StyledTitle>Title</StyledTitle> <StyledBox>Box</StyledBox> </div> ) } } ReactDOM.render(<App />, document.querySelector("#app"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

https://jsfiddle.net/Constantinff/g357tfv9/8/

Title不会将任何道具传播到h1 Box起作用是因为您将rest作为React.createElement的道具React.createElement - 您需要对h1执行相同的操作。

 const Title = ({ children, ...rest }) => { return (<h1 data-this-works="test" {...rest}>{children}</h1>) } const Box = ({ children, ...rest }) => { return React.createElement('span', rest, children) } const styleComponent = BaseComponent => ({children, ...props}) => { const style = {backgroundColor: 'green'} return ( <BaseComponent style={style} {...props} > {children} </BaseComponent> ); } const StyledTitle = styleComponent(Title) const StyledBox = styleComponent(Box) class App extends React.Component { render() { return ( <div> <StyledTitle>Title</StyledTitle> <StyledBox>Box</StyledBox> </div> ) } } ReactDOM.render(<App />, document.querySelector("#app"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM