react16中ref的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24147051/article/details/81218688

在 React16 新版本中,新引入了 React.createRefReact.forwardRef 两个 API,有计划移除老的 string ref,使 ref 的使用更加便捷与明确。如果你的应用已经升级到 React16.3+ 版本,那就放心大胆使用 React.createRef 吧,如果暂时没有的话,建议使用 callback ref 来代替 string ref

string ref 使用

class MyComponent extends React.Component {
  componentDidMount() {
    this.refs.myRef.focus();
  }
  render() {
    return <input ref="myRef" />;
  }
}

callback ref 使用

class MyComponent extends React.Component {
  componentDidMount() {
    this.myRef.focus();
  }
  render() {
    return <input ref={(ele) => {
      this.myRef = ele;
    }} />;
  }
}

React.createRef 使用

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    this.myRef.current.focus();
  }
  render() {
    return <input ref={this.myRef} />;
  }
}

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/81218688