组件实例中的三大属性
一、类组件中的state
1、state属性只存在于类组件的实例中,可通过类的构造器给state状态初始化。
2、在16.14.0当前版本中,state的值默认为null,往前的版本默认值可能不同,state存储格式为json。
例子:
//创建类组件
class Weather extends React.Component {
constructor() {
super();
this.state = { isHot: false };
}
render() {
}
}
3、在组件中不能通过直接实例.state来更改组件的状态,这是React不允许的,需要调用setState()方法来修改组件的状态,React才会重新进行渲染页面
4、使用setState()方法对状态是进行合并,不是替换。
注意:
- 在组件render中的this是实例对象。
- 在实例中的自定义方法this是undefined.如何解决?
- 强制绑定this,通过函数对象的bind()
- 使用箭头函数
二、类组件中的props
1、可在类组件实例标签中传递值
2、标签的所有属性都保存在props中(传递自动收集)
3、每个标签中都有props属性
注意:
组件内部不能修改props数据
例:
let p = {name : 'jerry',age : '19',sex : '男'}
ReactDOM.render(<Person {...p}/>,document.getElementById("box"));
3、类组件属性值限制及默认值
例:
<!-- 用于对组件标签属性的限制 -->
<script src="https://cdn.bootcdn.net/ajax/libs/prop-types/15.7.2/prop-types.js"></script>
//用于对标签属性值进行限制
Person.propTypes = {
name : PropTypes.string.isRequired,
age : PropTypes.number,
speak : PropTypes.func
}
//用于对组件标签属性赋默认值
Person.defaultProps = {
name : '老刘',
sex : '男'
}
let p = {name : '老刘' ,age : '19',sex : '男'}
ReactDOM.render(<Person age = {18} sex = '男' speak = {speak}/>,document.getElementById("box"));
function speak(){
console.log("说话");
}
4、类组件构造器是否传递props、super是否接受props,取决与在构造器中是否通过this来获取props。
三、类组件中的refs
作用
1、可在组件实例中,通过ref获取真实DOM
- 字符串类型ref创建
<input ref="input1" type="text" />
- 回调类型的ref创建
<input ref={(currentNode) => {this.input1 = currentNode}} type="text" />
- createRef创建
ref2 = React.createRef();
<input ref={this.ref2} onBlur = {this.showData2} type="text" />
showData2 = ()=>{
const {current} = this.ref2;
alert(current.value)
}
2、回调函数ref的调用次数
使用内联函数的ref,在DOM重新渲染时,会重复调用,第一次调用传入的节点为null,第二次传入真实的节点。
官方给出的解决方式:使用class绑定函数可以解决重复调用的问题,不过此问题无关紧要