react ref

2018-11-14  本文已影响12人  c33f7942e551

在 React16 新版本中,新引入了 React.createRef 与 React.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} />;

  }

}

原文:https://blog.csdn.net/qq_24147051/article/details/81218688

上一篇 下一篇

猜你喜欢

热点阅读