加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 在构造函数中访问Props值

发布时间:2020-12-15 09:32:27 所属栏目:百科 来源:网络整理
导读:我使用以下代码尝试通过访问props值来设置初始状态.我以为我可以通过访问(props)值来实现它,但它似乎是空的. constructor(props) { super(props); //this.renderRowForMain = this.renderRowForMain.bind(this); this.state = { show: props.showModal,}; }
我使用以下代码尝试通过访问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.

解决方法

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

例如:< MyComponent showModal = {true} />

然后,你将能够看到:

constructor(props) {
    super(props);

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

希望这可以帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读