10
0

9.生命周期.html 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <!-- jsx 语法浏览器不识别 jsx => js 浏览器可识别的语言 -->
  8. <script src="./babel.min.js"></script>
  9. <!-- react的核心库 -->
  10. <script src="./react.development.js"></script>
  11. <!-- 解析react中的dom库 -->
  12. <script src="./react-dom.development.js"></script>
  13. </head>
  14. <body>
  15. <div id="root"></div>
  16. <script type="text/babel">
  17. let root = ReactDOM.createRoot(document.getElementById("root"));
  18. function App() {
  19. return (
  20. <div>
  21. <h1>Hello, React!</h1>
  22. <Flower num={2} />
  23. </div>
  24. );
  25. }
  26. class Flower extends React.Component {
  27. constructor(props) {
  28. super(props);
  29. // props state 可以改变页面
  30. // props 只读 不修改
  31. // state 可修改
  32. this.state = {
  33. currentTime: new Date(),
  34. count: 0
  35. };
  36. }
  37. // 挂载
  38. componentDidMount() {
  39. console.log("挂载");
  40. console.log(this.props)
  41. this.timer = setInterval(() => {
  42. // currentTime: new Date()
  43. // 在react中 响应式更新状态 唯一方法:调用组件实例的setState方法
  44. // setState方法 在修改状态时候 就是新值 与 旧值合并后在覆盖掉旧状态
  45. // this.setState({
  46. // currentTime: new Date(),
  47. // // count: count + 1
  48. // })
  49. this.setState((state, props) => ({
  50. // console.log(state,props),
  51. currentTime: new Date(),
  52. count: state.count + 1 + props.num
  53. // counter: state.counter + props.increment,
  54. }));
  55. }, 1000);
  56. }
  57. // 更新
  58. componentDidUpdate() {
  59. console.log("更新");
  60. }
  61. // 卸载
  62. componentWillUnmount() {
  63. clearInterval(this.timer);
  64. }
  65. render() {
  66. // this.state.currentTime = 30;
  67. // console.log(this.state.count)
  68. return (
  69. <div>
  70. <h1>React</h1>
  71. <h3>{this.state.count}</h3>
  72. <p>当前时间:{this.state.currentTime.toLocaleString()}</p>
  73. </div>
  74. );
  75. }
  76. }
  77. root.render(<App />);
  78. </script>
  79. </body>
  80. </html>