框架学习React

010|React之Ref&DOM

2017-06-07  本文已影响133人  中年小钢炮

ref是React组件中的一个特殊特性(attribute),它指向一个函数,暂叫ref函数。

当组件mount或unmount时ref函数会被调用,基参数是原始的DOM对象或null。当ref函数用在自定义组件上时,其参数为组件对象的引用。

因此,我们可以使用ref函数来获取原始DOM对象。
一个示例代码如下:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in an instance field (for example, this.textInput).
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} /> // 使用ref函数获取 input DOM
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

一个更精练的ref可以如下:

ref={input => this.textInput = input}.

ref函数将会在componentDidMount之前被调用:

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }

  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

注意:ref函数无法应用于函数式组件上。如:

function MyFunctionalComponent() {
  return <input />;
}

class Parent extends React.Component {
  render() {
    // This will *not* work!
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} /> // 因MyFunctionalComponent是函数式组件,因此此处ref无效
    );
  }
}

但函数式组件内部是可以使用的:

function CustomTextInput(props) {
  // textInput must be declared here so the ref callback can refer to it
  let textInput = null;

  function handleClick() {
    textInput.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={(input) => { textInput = input; }} /> // ref是否有效取决于标签
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );  
}

父级为了获取子级原始DOM元素,可以将一个set函数赋值给子级的props属性,子级中再将此props属性赋值为ref函数。实现过程如下:

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

上述代码是一个两级传递,实际上三级传递的实现也是类似,通过props属性一层一层往下传。

React中什么是Uncontrolled Component?

好,这一节就到这里。Ref函数是React中一个非常重要的技巧,希望你掌握了。后续我将介绍更多React技术细节,来慢慢解答上述问题。

想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!微信号:iTekka。

上一篇下一篇

猜你喜欢

热点阅读