【问题标题】:Change state of member variable in React not working在 React 中更改成员变量的状态不起作用
【发布时间】:2018-10-12 17:10:57
【问题描述】:

我有一个 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"};
    }
    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>
        );
    }
}

【问题讨论】:

    标签: javascript html reactjs setstate


    【解决方案1】:

    您不能更改子组件的状态。相反,您应该使用道具:

    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>
        );
      }
    }
    

    【讨论】:

    • 我想让我的类由其他类的几个元素组成,并在给定事件触发器的情况下进行更新,并基于此进行不同的渲染基本上,onClick 会将文本从“否”更改为“是” " 我该怎么做呢?
    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2020-05-19
    • 2019-09-08
    相关资源
    最近更新 更多