加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React学习之进阶ref的必要性(十三)

发布时间:2020-12-15 07:29:20 所属栏目:百科 来源:网络整理
导读:在一般的数据流中也就是从上而下的单向数据流中,我们一般都是父组件要影响控制子组件必须要通过 props 来处理,即便是之前讲过 this.state ,但是那个东西也是针对自己的,而不是增对其它组件的,组件之间的影响到目前为止只能通过 props 来处理,这会非常

在一般的数据流中也就是从上而下的单向数据流中,我们一般都是父组件要影响控制子组件必须要通过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>
    );
  }
}

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

2.为类组件增加ref

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

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }
  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

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

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

function MyFunctionalComponent() {
  return <input />;
}
class Parent extends React.Component {
  render() {
    // 这将会出问题
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

就前面一篇博客提到的,我们应该将函数式组件转换为类组件,才能使用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>
  );  
}

不要过度的使用ref属性

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

过时的refs字符串

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

下一篇将讲React中的非控制型组件

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读