React State属性

import React from 'react'
export default class ComponentHeader extends React.Component {
  constructor () {
    super() // 调用基类的所有初始化方法
    this.state = {username: 'Mo'}
  }
  render() {
    setTimeout(()=>{
      this.setState({username: 'Ko'})
    }, 3000)
    return ( // 只能有一个节点
      

{this.state.username}

) } }

1. 初始化

this.state = {username: 'Mo'}

2. 初始化放置在构造函数constructor里

3.修改state

this.setState({username: 'Ko'})

4.state 的作用域只属于当前的类,不污染其他模块

5.触发改变state

  constructor () {
    super() // 调用基类的所有初始化方法
    this.state = {age: '10'}
  }
  changeUserInfo () {
    this.setState({age:38})
  }
render() {
    return (
      <div>
        

{this.state.age}

'button' value='按钮' onClick={this.changeUserInfo.bind(this)} />

div> ) }

你可能感兴趣的:(React State属性)