源代码 :
点击运行
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React 实例</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> <style> button { height: 40px; width: 200px; } .warning { background-color: red; text-align: center; width: 100%; padding: 10px; font-size: 14pt; color: white; } </style> </head> <body> <div id="example"></div> <script type="text/babel"> function WarningBanner(props) { if (!props.warn) { return null; } return ( <div className="warning"> 警告! </div> ); } class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind(this); } handleToggleClick() { this.setState(prevState => ({ showWarning: !prevState.showWarning })); } render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? '隐藏' : '显示'} </button> </div> ); } } ReactDOM.render( <Page />, document.getElementById('example') ); </script> </body> </html>
运行结果