我第一次弄乱React.js,找不到通过click事件在页面上显示或隐藏内容的方法。我没有在页面上加载任何其他库,所以我在寻找使用React库的本机方法。这是我到目前为止所拥有的。我想在click事件触发时显示结果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);
在onClick回调中,调用状态挂钩的setter函数以更新状态并重新渲染:
onClick
const Search = () => { const [showResults, setShowResults] = React.useState(false) const onClick = () => setShowResults(true) return ( <div> <input type="submit" value="Search" onClick={onClick} /> { showResults ? <Results /> : null } </div> ) } const Results = () => ( <div id="results" className="search-results"> Some Results </div> ) ReactDOM.render(<Search />, document.querySelector("#container")) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="container"> <!-- This element's contents will be replaced with your component. --> </div>
关键是使用来更新点击处理程序中组件的状态setState。应用状态更改后,将render使用新状态再次调用该方法:
setState
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>