美文网首页
refs and the dom

refs and the dom

作者: 三元一只十元三只 | 来源:发表于2020-04-20 09:10 被阅读0次

React数据流是单向的,通过props由父组件向子组件传递数据,如果要修改子组件,需要修改props来重新渲染子组件。refs就是另一种方法,强制修改子组件。

refs使用React.createRef() 创建,并且通过ref属性附加到React元素中。在组件的构造函数中,可以将refs分配给实例属性,以便在整个组件中使用他们。

访问refs使用current属性。

为DOM元素添加refs

class myComponent extends React.component{
    constructor(props) { 
        super(props);
        this.myRefs = React.createRef();
        this.focusTextInput = this.focusTextInput.bind(this);
    }

    focusTextInput () {
        this.myRefs.current.focus();
    }


    render() {
        return (
            <div>
                <div ref={this.myRefs} />;
                <div type="button" onClick = {this.focusTextInput} />
    }
}

这个例子会在点击按钮后第一个input框获取焦点。

为class元素添加refs

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

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

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

函数组件不能使用refs属性,因为函数组件没有实例。如果要使用该功能,可以使用forwardRef或者将组件转化为class

相关文章

网友评论

      本文标题:refs and the dom

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