在构造函数中访问Props值

时间:2017-05-11 16:29:49

标签: reactjs react-native

我正在使用以下代码尝试通过访问props值来设置初始状态。我认为我可以通过访问(props)值来实现它,但它似乎是空的。

constructor(props) {
    super(props);

    //this.renderRowForMain = this.renderRowForMain.bind(this);

    this.state = {
      show: props.showModal,
    };

  }

如果我只是将以下内容放在render()中,那么它似乎正好可以加载。

this.state = {
          show: this.props.showModal,
        };

我想要做的是最初将showModal状态设置为true,然后当点击关闭按钮时将状态更改为false。

1 个答案:

答案 0 :(得分:0)

首先像这样在构造函数中使用props数据。

constructor(props) {
super(props);

this.state = {
  show: props.showModal, // true
  };
}

然后假设您要单击按钮并显示状态数据...以便我们应该像这样创建点击功能

onClick(){
console.log(this.state.show);  //display show variable data in state in console
}

每当您单击按钮然后在控制台中显示数据

并创建一个按钮

<button className="button" onClick={() => this.onClick()}>Click Me</button>
相关问题