关于react.js:React-state-基础使用

51次阅读

共计 838 个字符,预计需要花费 3 分钟才能阅读完成。

import React, {Component} from ‘react’

class index extends Component {
constructor(props) {

 super(props)
 this.state = {
   count:10,
   name:'小刘',
   obj: {
     a: 1,
     b: 2,
     c:3,
   } 
 }

}

setName() {

//  const {name} = this.state;
 this.setState({name:'老刘'})

}

setA() {

 //  const {obj} = this.state;
   const obj = Object.assign({},this.state.obj, { a:10})
 setTimeout(() => {
   this.setState({obj:obj})
  },1000)
}

setB() {

 const b={b:20}
 const obj = {
   ...this.state.obj,
   ...b
 }
 setTimeout(() => {
   this.setState({obj:obj})
 },2000)
 

}
componentDidMount() {

}
render() {

 const {name ,obj ,count} = this.state;
 
return (
  <div>
   
    {name}
    <button onClick={() => { this.setName() }}> 点击变强 </button> <br/>
    {count}
    <button onClick={() => this.setState({ count: count + 1})}>count+1</button> <br/>
    
    Obj a 的值是 {obj.a}  <br/>
    Obj b 的值是 {obj.b} <br/>
    Obj c 的值是 {obj.c} <br/>
    <button onClick={()=>{this.setA()}}> 1 秒后批改 a 的值 </button>
    <button onClick={()=>{this.setB()}}> 2 秒后批改 b 的值 </button>
    
  </div>
)

}
}

export default index

正文完
 0