一、React初体验-事件绑定this-类组件

70 阅读1分钟
// 1. react18
const root = ReactDOM.createRoot(document.querySelector('#root'))

// 2. render函数接收一个App组件
root.render(<App />)

// 3. react组件封装
/**
 * 3.1 组件分类
 * 类组件
 * 函数式组件
 */

// 3.1.1 类组件
class App extends React.Component {
  constructor() {
    super() // 组件类继承需要调用super方法
    // 数据
    this.state = {
      msg: '默认值'
    }
    this.btnClick = this.btnClick.bind(this) // 提前绑定
  }
  
  // 方法
  btnClick() {
    // 我们需要去修改msg的值 并重新执行render函数渲染
    // 严格模式下默认调用函数为undefined
    console.log(this)  // 调用的时候需要显示绑定this
    // 调用来自React.Component的继承方法
    this.setState({
      msg: '修改后的值'
    })
  }

  // 渲染内容
  render() {
    return (
      <div>
        <h2>{ this.state.msg }</h2>
        <button onClick={this.btnClick.bind(this)}>修改</button>  
      </div>
    )
  }
}