我第一次使用 React.js,找不到通过点击事件在页面上显示或隐藏某些内容的方法。我没有将任何其他库加载到页面中,因此我正在寻找使用 React 库的本地方式。这就是我到目前为止所拥有的。我想在点击事件触发时显示结果 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回调中,调用state hook 的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>
JSFiddle
关键是在点击处理程序中使用更新组件的状态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>