Skip to content

Latest commit

 

History

History
75 lines (64 loc) · 1.98 KB

10.Refs & DOM.md

File metadata and controls

75 lines (64 loc) · 1.98 KB

Refs and the DOM

通常情况下props是组件与组件之间通信的唯一方式,然而有时候会遇到需要在数据流之外紧急修改一些child(React component也可能是DOM),为解决这些问题React提供了一个escape hatch转义窗口

什么时候使用refs

以下有几种很好的适用场景:

  • 管理文本框获取焦点、文本选择、媒体资源重放
  • 触发要立即执行的动画
  • 和三方DOM库合并

但是一定要避免过度使用refs

DOM元素添加ref

React支持向任何组件添加特殊的属性。ref接收一个回调函数,这个回调函数在组件mount 或者unmount的时候立即执行。当向DOM元素添加ref时,回调函数会把当前DOM元素当做参数传入

// 点击button时,input获取焦点
class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.focus();
  }

  render() {
    // 参数input是当前元素本身
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

这个案例中其实可以通过获取DOM来避免使用ref

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

    focus() {
    // 通过原生DOM操作来实现
        let inp=document.getElementsByClassName("input1")[0]
        inp.focus()
    }

    render() {
        return (
            <div>
                <input type="text" className="input1"/>
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.focus}
                />
            </div>
        );
    }
}

待更新...