![](/img/trans.png)
[英]Is it a good practice to use getter to render another component inside React component?
[英]Render a component inside another React
好的,我迷路了,我嘗試在舊線程中找到答案,但找不到任何可以幫助我的東西。 我的代碼看起來像這樣
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'));
問題是它只呈現背景組件,而計數組件仍然不可見,沒有錯誤或任何東西,我不知道為什么,很高興有任何幫助。
您想在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.