Refs and the DOM

提供了一个指向Dom的引用,可以访问Dom节点或者已经创建的React组件.

使用时机

  • 焦点处理、文本选择、媒体文件的回放

  • 触发一个动画命令

  • 集成第三方的Dom库时

    不要过度使用Refs

创建Refs

通过React.createRef()方法来创建,示例:

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

Refs使用

通过const input = this.myRef就可以获取到input这个Dom了.

组件加载完获取焦点的示例:

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

    componentDidMount() {
      if(this.myRef) {
        this.myRef.current.focus();
      }
    }

    render() {
      return (
        <div>
          <input defaultValue="no focus"/>
          <p/>
          <input ref={this.myRef} defaultValue="has focus"/>
        </div>
      )
    }
  }

在线示例

通过回调的方法创建

子组件:

  const CustomTextInput = ({inputRef}) => {
    return <input ref={inputRef}/>
  }

父组件:

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

在线示例

results matching ""

    No results matching ""