React笔记:ref注意事项

【一】使用ref必须用在【类型式的组件】才起作用,用在【函数式的组件】是无效的。

下面这个例子用在了【函数式的组件】上,所以是无效的:

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

class Parent extends React.Component {
  render() {
    // This will *not* work!
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

下面这个例子是正确的用法:

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

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

【二】ref用在普通的 DOM 元素 上时,DOM 元素 作为ref的参数进行使用;

     ref用在 组件 上时,组件 作为ref的参数进行使用;

原文地址:https://www.cnblogs.com/lishidefengchen/p/8659917.html