[英]Change state of member variable in React not working
I have a class Box2 which I have made an instance of in Box1 我有一个Box2类,我在Box1中做了一个实例
Box1 just renders the instance which is has of Box2 however using setState for that instance that I have it doesnt change Box1只是呈现具有Box2的实例,但是对我拥有的实例使用setState不会改变
import React from 'react';
import ReactDOM from 'react-dom';
class Box2 extends React.Component{
constructor(props){
super(props);
this.state={text:"No"};
}
render(){
return(
<h1>
{this.state.text}
</h1>
);
}
}
export default class Box1 extends React.Component{
Elements=[];
constructor(){
super();
this.Elements[0]=new Box2();
this.Elements[0].setState({text:"YES"});
}
render(){
return(<div>
{this.Elements.map((e)=>e.render())};
</div>
);
}
}
You can not change state of your child components. 您无法更改子组件的状态。 Instead you should use props:
相反,您应该使用道具:
class Box2 extends React.Component{
render(){
return(
<h1 onClick={this.props.onClick}>
{this.props.text}
</h1>
);
}
}
export default class Box1 extends React.Component {
constructor(props) {
super(props);
this.state = {
isBox2Yes: true,
};
this.onBoxClick = this.onBoxClick.bind(this);
}
onBoxClick() {
this.setState({ isBox2Yes: !this.state.isBox2Yes });
}
render(){
return(
<div>
<Box2
text={this.state.isBox2Yes ? 'YES' : 'NO'}
onClick={this.onBoxClick}
/>
</div>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.