[英]pass children to react component
如何将孩子在React.render
中编写的内容React.render
给组件? 我尝试使用Component
重写该代码( https://pastebin.com/Pwtnd7Yh ),如何将子代传递给该组件,在示例代码作者中写...rest
是什么,以及如何将数据传递给我的组件?
<script type="text/babel">
const root = document.getElementById("root");
class Block extends React.Component{
constructor(props){
super(props);
this.state = {size: props.size, style: props.style};
}
render(){
const sizeClassName = this.state.size ? `box--${this.state.size}` : '';
return(
<div className={`box ${sizeClassName}`} style={{paddingLeft: 20, ...this.state.style}} />
)
}
}
ReactDOM.render(
<div>
<Block size='small' style={{backgroundColor: 'lightblue'}}>small box</Block>
<Block size='medium' style={{backgroundColor: 'orange'}}>medium box</Block>
</div>,
root
)
</script>
要解决此问题,只需添加`{... this.props}作为属性。
render(){
const sizeClassName = this.state.size ? `box--${this.state.size}` : '';
return(
<div className={`box ${sizeClassName}`} style={{paddingLeft: 20, ...this.state.style}} {...this.props} />
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.