13.类组件.html 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. <script src="./babel.min.js"></script>
  8. <script src="./react.development.js"></script>
  9. <script src="./react-dom.development.js"></script>
  10. </head>
  11. <body>
  12. <div id="root"></div>
  13. <script type="text/babel">
  14. // props
  15. // state
  16. class News extends React.Component {
  17. state = {
  18. name: '图图',
  19. age: 3,
  20. sum: 0,
  21. isShow: true
  22. }
  23. // handleClick = () => {
  24. // console.log("触发")
  25. // // this.state.age += 2;
  26. // console.log(this)
  27. // }
  28. handleClick() {
  29. this.setState({
  30. age: this.state.age + 10,
  31. name: 'Tom'
  32. })
  33. }
  34. handleAdd() {
  35. this.setState((val) => ({ sum: val.sum + 1 })
  36. )
  37. }
  38. handleReduce() {
  39. this.setState({
  40. sum: this.state.sum - 1
  41. })
  42. }
  43. render() {
  44. // console.log(this, '11')
  45. // return (
  46. // <div>
  47. // <h1>父组件</h1>
  48. // <h1>数值:{this.state.sum}</h1>
  49. // <button onClick={this.handleAdd.bind(this)}>+1</button>
  50. // <button onClick={this.handleReduce.bind(this)}>-1</button>
  51. // <h3>我叫{this.state.name},今年{this.state.age}岁</h3>
  52. // <button onClick={this.handleClick.bind(this)}>+2</button>
  53. // <button onClick={() => {
  54. // console.log(this)
  55. // }}>+2</button>
  56. // <Child userInfo={this.state.name} />
  57. // </div >
  58. // )
  59. return <Child userInfo={this.state.name} />
  60. }
  61. }
  62. class Child extends React.Component {
  63. constructor() {
  64. console.log('con')
  65. super();
  66. this.state = {
  67. weather: "晴天"
  68. }
  69. this.handleWeather = this.handleWeather.bind(this);
  70. }
  71. // 挂载:constructor render componentDidMount
  72. // 更新:render componentDidUpdate
  73. componentDidMount() {
  74. console.log("挂载")
  75. }
  76. componentDidUpdate() {
  77. console.log("222")
  78. }
  79. componentWillUnMount() {
  80. console.log("卸载")
  81. }
  82. handleWeather() {
  83. this.setState({
  84. weather: "雨天"
  85. })
  86. console.log(this)
  87. }
  88. render() {
  89. console.log("render")
  90. return (
  91. <div>
  92. <h1>外面是{this.state.weather},我叫{this.props.userInfo}</h1>
  93. <button onClick={this.handleWeather}>修改天气</button>
  94. </div>
  95. )
  96. }
  97. }
  98. const element = <News />
  99. const container = document.getElementById("root");
  100. const root = ReactDOM.createRoot(container)
  101. root.render(element);
  102. </script>
  103. </body>
  104. </html>