源代码:
下载代码
AI 编程工具
点击运行
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>菜鸟教程 React 实例</title> <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/react/18.2.0/umd/react.production.min.js" ></script> <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/react-dom/18.2.0/umd/react-dom.production.min.js"></script> <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/babel-standalone/6.26.0/babel.min.js" ></script> </head> <body> <div id="root"></div> <script type="text/babel"> class Container extends React.Component { constructor(props) { super(props); this.state = {show: true}; } delHeader = () => { this.setState({show: false}); } render() { let myheader; if (this.state.show) { myheader = <Child />; }; return ( <div> {myheader} <button type="button" onClick={this.delHeader}>删除标题组建</button> </div> ); } } class Child extends React.Component { componentWillUnmount() { alert("标题组件即将卸载。"); } render() { return ( <h1>Hello Runoob!</h1> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Container />); </script> </body> </html>
运行结果: