react之ref

转自: https://blog.csdn.net/qq_18661257/article/details/63683212

在一般的数据流中也就是从上而下的单向数据流中,我们一般都是父组件要影响控制子组件必须要通过props来处理,即便是之前讲过this.state,但是那个东西也是针对自己的,而不是增对其它组件的,组件之间的影响到目前为止只能通过props来处理,这会非常的麻烦,所以React提供了一个特殊的接口来处理这种事件。

ref的用处

ref用在处理表单空间聚焦,文本选择,媒体播放以及触发动画效果等等

官方强调不要用ref直接去做非常明显的事件,比如说Dialog组件打开和关闭的open()close()可以通过isOpen去控制,而不是明显的函数处理

ref是一个React的非常特殊的属性,这个属性一定是接受一个回调函数,这个回调函数会在组件渲染时进行执行一遍,在从视图中撤出来时会执行一遍

1.为DOM元素增加ref

当我们用为HTML元素增加ref属性时,我们的ref会传递一个参数给回调函数

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }
  focus() {
    this.textInput.focus();
  }
  render() {
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

React在组件渲染时调用回调函数时,这个参数就是DOM元素本身,在撤离视图时会返回null

2.为类组件增加ref

HTML元素一样,为类组件调用ref回调函数的时机是一样的,只是参数是组件的一个实例

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }
  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3.ref在函数式组件中不可用

不要企图在函数式组件中使用ref属性来进行回调函数的绑定,因为函数式组件是没有实例的,准确的说函数式组件不是一个真正的类

function MyFunctionalComponent() {
  return <input />;
}
class Parent extends React.Component {
  render() {
    // 这将会出问题
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} />
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

就前面一篇博客提到的,我们应该将函数式组件转换为类组件,才能使用ref属性,当然虽然无法对函数式组件使用ref属性,但是为函数式组件里面的HTML元素和类组件使用ref属性是可以的

function CustomTextInput(props) {
  let textInput = null;
  function handleClick() {
    textInput.focus();
  }
  return (
    <div>
      <input
        type="text"
        ref={(input) => { textInput = input; }} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

不要过度的使用ref属性

ref从一定程度上增加了组件之间的耦合性,导致难以分离,所以如果可以用props来处理的事情,尽量不要用ref来处理

过时的refs字符串

在以前的一些React版本通过this.refs可以获取一个字符串,这个方法在将来会被抛弃所以请不要使用,即便是ref可以设置为一个字符串,但是强烈建议用回调函数

猜你喜欢

转载自blog.csdn.net/gytha_1/article/details/80240911
今日推荐