简体   繁体   中英

How to hide a component using button in reactjs?

I have read the method about how to show/hide a component and I made some modification to it, however, my modification is not working. enter link description here

My Not working code is 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> 

I have two goals: 1. The first goal is to add a button to close this welcome box. 2. The second goal is to add a cookie to it, in order to show this welcome box to user when they visit this website for the first time, and once they click to close it, it will not show up again if not clear the cookie.

You have to pass the onClick function as a prop from ShowHide to Child .

<Child onClick={this.onClick} />

Then your button in Child would look like this

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

You also have a little typo in your initialState, you wrote ture instead of true .

As an additional tip, I'd recommend you to use ES6 classes instead of React's createClass. Better performance and more standard :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM