Javascript 在React not working中更改成员变量的状态
我有一个类Box2,我在Box1中做了一个实例 Box1只渲染Box2的实例,但是使用我拥有的实例的setState不会改变Javascript 在React not working中更改成员变量的状态,javascript,html,reactjs,setstate,Javascript,Html,Reactjs,Setstate,我有一个类Box2,我在Box1中做了一个实例 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"}; } r
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>
);
}
}
从“React”导入React;
从“react dom”导入react dom;
类Box2扩展了React.Component{
建造师(道具){
超级(道具);
this.state={text:“No”};
}
render(){
返回(
{this.state.text}
);
}
}
导出默认类Box1扩展React.Component{
元素=[];
构造函数(){
超级();
this.Elements[0]=new Box2();
this.Elements[0].setState({text:“YES”});
}
render(){
返回(
{this.Elements.map((e)=>e.render())};
);
}
}
您不能更改子组件的状态。相反,你应该使用道具:
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>
);
}
}
class-Box2扩展了React.Component{
render(){
返回(
{this.props.text}
);
}
}
导出默认类Box1扩展React.Component{
建造师(道具){
超级(道具);
此.state={
isBox2Yes:是的,
};
this.onBoxClick=this.onBoxClick.bind(this);
}
onBoxClick(){
this.setState({isBox2Yes:!this.state.isBox2Yes});
}
render(){
返回(
);
}
}
您不能更改子组件的状态。相反,你应该使用道具:
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>
);
}
}
class-Box2扩展了React.Component{
render(){
返回(
{this.props.text}
);
}
}
导出默认类Box1扩展React.Component{
建造师(道具){
超级(道具);
此.state={
isBox2Yes:是的,
};
this.onBoxClick=this.onBoxClick.bind(this);
}
onBoxClick(){
this.setState({isBox2Yes:!this.state.isBox2Yes});
}
render(){
返回(
);
}
}
我想让我的类由其他类的几个元素组成,并在给定事件触发器的情况下进行更新,并在此基础上进行不同的渲染。基本上,单击它会将文本从“否”更改为“是”我想让我的类由其他类的几个元素组成,并在给定事件触发器的情况下进行更新,并在此基础上进行不同的呈现基本上,单击它会将文本从“否”更改为“是”,我该怎么做?