Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - 在React中显示或隐藏元素(Show or hide element in React)

I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event.(我第一次弄乱React.js,找不到通过click事件在页面上显示或隐藏内容的方法。)

I am not loading any other library to the page, so I am looking for some native way using the React library.(我没有在页面上加载任何其他库,因此我正在寻找使用React库的本机方法。) This is what I have so far.(到目前为止,这就是我所拥有的。) I would like to show the results div when the click event fires.(当点击事件触发时,我想显示结果div。) var Search= React.createClass({ handleClick: function (event) { console.log(this.prop); }, render: function () { return ( <div className="date-range"> <input type="submit" value="Search" onClick={this.handleClick} /> </div> ); } }); var Results = React.createClass({ render: function () { return ( <div id="results" className="search-results"> Some Results </div> ); } }); React.renderComponent(<Search /> , document.body);   ask by user1725382 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key is to update the state of the component in the click handler using setState .(关键是使用setState更新点击处理程序中组件的状态。)

When the state changes get applied, the render method gets called again with the new state:(应用状态更改后,将使用新状态再次调用render方法:) var Search = React.createClass({ getInitialState: function() { return { showResults: false }; }, onClick: function() { this.setState({ showResults: true }); }, render: function() { return ( <div> <input type="submit" value="Search" onClick={this.onClick} /> { this.state.showResults ? <Results /> : null } </div> ); } }); var Results = React.createClass({ render: function() { return ( <div id="results" className="search-results"> Some Results </div> ); } }); ReactDOM.render( <Search /> , document.getElementById('container')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script> <div id="container"> <!-- This element's contents will be replaced with your component. --> </div> JSFiddle(JSFiddle)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...