state,props,refs属性
2018-07-25 本文已影响0人
QinRenMin
react的三大属性state props refs
- state
状态三部曲:
1)初始化状态值
在constructor中初始化
this.state = {
name:value
}
2)读取state值
const {name} = this.state;
3)更新状态值(在定义的函数内)
const name = this.state.name;
this.setState({name})
- props
指定默认属性
Mycomponent.defaultProps={
age:18,
sex:'boy'
};
约定属性值类型以及必要性
Mycomponent.propTypes = {
name : PropTypes.String.isRequired,
age: PropTypes.number
};
- refs(尽量避免使用Refs)
用户名<input type="text" ref={input => this.nameInput=input}/>
const name = this.nameInput.value; //或得到input框的值