react之state
之前说到react中的props属性,现在说react中和props一样重要的state属性
state的意思为'状态' 是可以改变的 与props就恰恰相反 props的值是可读的,并不能改变,而state就恰恰可以
看代码:
import React , {Component} from 'react';
import PropTypes from 'prop-types'
class Xhao extends Component {
constructor(props){
super(props);
this.state = {
stateage:this.props.age
}
}
onAdd(){
this.setState({
stateage:this.state.stateage+=3
})
}
render(){
console.log(this.props);
console.log(this.props.children)
return (
<div>
<span>我叫{this.props.name},今年已经{this.state.stateage}岁了</span>
<button onClick={this.onAdd.bind(this)}>增加年纪</button>
</div>
)
}
}
export default Xhao
1. 首先给class 定义个constructor(constructor和class都是es6提供的,并不是react提供的语法),里面传入props属性 接收从父组件传来的参数。然后我们就能拿到 name age的值了
2. 然后在constructor里面定义一个state对象。 并将其设置为 stateage: this.props.age 键为stateage 值为:this.props.age. === stateage:18
3. 在button上定义一个函数 为onAdd()的函数
4. 然后在render里面写上函数
onAdd(){ this.setState({
stateage: this.state.stateage +=3
})}
看到这里不禁想问了,setState是什么? setState是 react中提供的一个函数,可以获取state定义的值
5. 最后在 <span>我叫{this.props.name},今年已经{this.state.stateage}岁了</span> 中 。 就可以点击按钮 在{stateage}上每次都+3了

浙公网安备 33010602011771号