【问题标题】:Accessing Props Value Inside Constructor在构造函数中访问道具值
【发布时间】:2017-10-10 18:56:08
【问题描述】:

我正在使用以下代码尝试通过访问 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。

【问题讨论】:

  • 看起来prop showModel 最初是空白或没有值,检查console.log(props.showModel)constructor 中的使用并查看结果。
  • IOS模拟器内部如何访问console.log?
  • 不知道,你也可以使用alert。检查这个,如何在 ios 模拟器中检查控制台:stackoverflow.com/questions/10165641/…
  • 在模拟器中,按 command + D 即可通过chrome窗口访问控制台

标签: reactjs react-native


【解决方案1】:

您应该在父组件中传递showModal 值。否则 props.showModal 将不会出现在您的构造函数中。 ​

例如:<MyComponent showModal={true} /> ​​​ 然后,您将能够看到: ​

constructor(props) {
    super(props);

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

希望对你有帮助

【讨论】:

    【解决方案2】:

    首先像这样在构造函数中使用道具数据..

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多