11.1. React-ref

149 阅读1分钟

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. 状态提升

  • 兄弟组件传递状态和属性可以把属性放在两者共同的父组件,通过父组件进行数据传递