1. ref
1.1. ref=字符串
赋值: ref={num} ; 使用 this.refs.num.value ;
1.2 ref=函数
赋值: ref={inst=>num = inst} ; 使用 this.num.value ;
1.3 ref最新
- 构造函数:
this.num = React.createRef(); - 赋值:
ref={this.num}; - 使用:
this.num.current.value; React.createRef()原理:
function createRef(){
return {current: null};
}
2. ref组件间传递
Form组件拿到TextInput组件中的input值Form组件:- 构造函数:
this.textInput = React.createRef(); - 赋值:
<TextInput ref={this.textInput} /> - 使用获取
TextInput组件中input焦点:this.textInput.current.textInput.current.focus()
- 构造函数:
TextInput组件:- 构造函数:
this.textInput = React.createRef(); - 赋值:
<input ref={this.textInput} />
- 构造函数:
3. ref: 函数组件使用
- 使用
React.forwardRef()对子函数组件进行包裹,返回的新组件,新组件放入父组件中,就可以使用props和ref
4. 受控和非受控组件
- 受控组件: 指的是
DOM元素的值存在DOM元素内部,不受React控制 - 非受控组件:
DOM元素的值受React状态控制
5. 状态提升
- 兄弟组件传递状态和属性可以把属性放在两者共同的父组件,通过父组件进行数据传递