美文网首页
React官网学习实践 - Refs & DOM

React官网学习实践 - Refs & DOM

作者: 张中华 | 来源:发表于2018-11-22 20:31 被阅读18次

在典型的 React 数据流中, 属性(props)是父组件与子代交互的唯一方式。要修改子组件,你需要通用新的 props 重新渲染它。但是,某些情况下你需要在典型数据流外强制修改子代。要修改的子代可以是 React 组件实例,也可以是 DOM 元素。

何时使用 Refs

下面是几个适合使用 refs 的情况:

处理焦点、文本选择或媒体控制。
触发强制动画。
集成第三方 DOM 库

如果可以通过声明式实现,则尽量避免使用 refs。

例如,不要在 Dialog 组件上直接暴露 open() 和 close() 方法,最好传递 isOpen 属性。

不要过度使用 Refs

为 DOM 元素添加 Ref

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // 直接使用原生 API 使 text 输入框获得焦点
    this.textInput.focus();
  }

  render() {
    // 使用 `ref` 的回调将 text 输入框的 DOM 节点存储到 React 
    // 实例上(比如 this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

为类组件添加 Ref

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

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

相关文章

网友评论

      本文标题:React官网学习实践 - Refs & DOM

      本文链接:https://www.haomeiwen.com/subject/ubzhqqtx.html