[英]Render a component inside another React
Ok i'm so lost, i tryied finding the answer in old threads but i couldn't find anything that would help me.好的,我迷路了,我尝试在旧线程中找到答案,但找不到任何可以帮助我的东西。 My code looks like this
我的代码看起来像这样
class Background extends React.Component{
constructor(props){
super(props);
this.state = {
bgColor: [
'red',
'blue',
'yellow',
],
selectedColor: ''
}
}
componentDidMount(){
this.getRandomColor();
}
getRandomColor(){
var item = this.state.bgColor[Math.floor(Math.random()*this.state.bgColor.length)];
this.setState({
selectedColor: item,
})
}
render(){
return(
<div style={{backgroundColor: this.state.selectedColor}}>
<h1>Quote Generator</h1>
</div>
)
}
}
class Count extends React.Component{
constructor(props){
super(props);
this.state={
count: 0
}
}
addNumber(){
this.setState({
count: this.state.count +1
})
}
render(){
return(
<div>
<h1>{this.state.count}</h1>
<button onClick={this.addNumber.bind(this)}>ADD A NUMBER</button>
</div>
);
}
}
class QuoteGenerator extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<Background>
<Count/>
</Background>
);
}
}
ReactDOM.render(<QuoteGenerator/>, document.getElementById('root'));
the problem is that it only renders the Background component, while the Count component remains invisible, no errors or anything, and i can't figure out why, any help is gladly appreciated.问题是它只呈现背景组件,而计数组件仍然不可见,没有错误或任何东西,我不知道为什么,很高兴有任何帮助。
You want to use props.children
in your Background
component您想在
Background
组件中使用props.children
render(){
return(
<div style={{backgroundColor: this.state.selectedColor}}>
<h1>Quote Generator</h1>
{this.props.children}
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.