在
onClick回调中,调用状态挂钩的setter函数以更新状态并重新渲染:
反应约2014年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使用新状态再次调用该方法:
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>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)