【问题标题】:How to hide a component using button in reactjs?如何在reactjs中使用按钮隐藏组件?
【发布时间】:2017-11-03 10:07:30
【问题描述】:

我已经阅读了有关如何显示/隐藏组件的方法并对其进行了一些修改,但是我的修改不起作用。enter link description here

我的无效代码在这里:

var Child = React.createClass({
  render: function() {
    return (
       <div className="container">
         <p>Welcome to our website</p>
         <button  onClick={this.onClick}>Click me to close</button>
       </div>
    );
  }
});

var ShowHide = React.createClass({
  getInitialState: function () {
    return { childVisible: ture };
  },
  
  render: function() {
    return(
      <div>
        {
          this.state.childVisible
            ? <Child />
            : null
        }
      </div>
    )
  },
  
  onClick: function() {
    this.setState({childVisible: !this.state.childVisible});
  }
});
 
React.render(<ShowHide />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

我有两个目标: 1.第一个目标是添加一个按钮来关闭这个欢迎框。 2. 第二个目标是给它添加一个cookie,以便用户第一次访问本网站时显示这个欢迎框,一旦点击关闭它,如果不清除它就不会再次显示饼干。

【问题讨论】:

    标签: javascript reactjs cookies


    【解决方案1】:

    您必须将 onClick 函数作为道具从ShowHide 传递给Child

    <Child onClick={this.onClick} />
    

    那么Child 中的按钮将如下所示

    <button onClick={this.props.onClick}>...</button>
    

    您的 initialState 中还有一个小错字,您写的是 ture 而不是 true

    【讨论】:

      【解决方案2】:

      作为附加提示,我建议您使用 ES6 类而不是 React 的 createClass。更好的性能和更标准的:D

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 2015-07-06
        • 2012-02-21
        • 2018-03-12
        • 1970-01-01
        相关资源
        最近更新 更多