React 中 Ref 的使用

为DOM元素添加Ref

//以下代码使用 ref 去存储 DOM 节点的引用
class Refs extends React.Component{
  constructor (props) {
    super(props);
    //将Ref在构造函数中,配置实例属性。以便整个组件能够访问。
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }
  focusTextInput(){
    //Ref这样理解:是一个储存DOM的引用,
    // 使用this.myRef.current来访问Ref,也就是访问DOM节点。
    // 注意,这个Ref就是要访问DDM节点用的
    const node = this.textInput.current;
    console.log(node);
    node.focus();
  }
  render () {
    //在 <input> 上关联ref属性,关联到 构造函数 中创建的 `textInput` 上
    return(
      <div>
        <input type="text" ref={this.textInput}/>
        <input type="button" value="Focus the text input" onClick={this.focusTextInput}/>
      </div>
    )
  }
}

包装上面的方法:

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();  }

  componentDidMount() {
    this.textInput.current.focusTextInput();  }

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