React从入门到精通系列之,14refs和DOM元素

3.7k 次阅读 · 读完需要 8 分钟

8

十四、refs和DOM元素

在典型的React数据流中,props是父组件与其子组件交互的唯一方式。 要修改子组件,需要使用一个新的props进行重新渲染。

但是,在某些情况下,您需要在典型数据流之外强制修改子组件。 要修改的子组件可以是React组件实例,也可以是DOM元素。 对于这两种情况,React提供了一个以下这样的功能。

通过ref属性设置回调函数

React提供可以附加到任何组件的特殊属性。 ref属性接受一个回调函数,回调函数将在组件被挂载或卸载后立即执行。

当在HTML元素上使用ref属性时,ref回调函数接收一个基础的DOM元素作为其参数。 例如,此代码使用ref回调函数来存储对DOM节点的引用:

import React from 'react';
import ReactDOM from 'react-dom';

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

    focus() {
        // textInput是一个标准的DOM元素
        this.textInput.focus();
    }

    render() {
        return (
            <div>
                <input type="text" ref={input => {
                    this.textInput = input;
                }}/>
                <input type="button" value="选中上面的text input" onClick={this.focus}/>
            </div>
        );
    }
}
ReactDOM.render(
    <CustomTextInput/>,
    document.getElementById('root')
);

当组件装载(mounting)时,React将使用DOM元素调用ref回调函数,并在卸载时用null调用它。

使用ref回调函数是为类设置一个属性来访问DOM元素的常见模式。 如果您目前正在使用this.refs.myRefName来访问DOM引用的话,我会建议你使用此模式。

当在自定义组件上使用ref属性时,ref回调接收组件的已装入的组件实例作为其参数。 例如,如果我们想要包装上面的CustomTextInput来模拟它在装载(mounting)后立即被点击:

class AutoFocusTextInput extends React.Component {
    componentDidMount() {
        this.textInput.focus();
    }
    render() {
        return (
            <CustomTextInput ref={input => {this.textInput = input; }} />
        );
    }
}

您不能在功能性组件上使用ref属性,因为它们没有实例。 但是,您可以使用功能性组件的render函数内的ref属性:

function CustomTextInput(props) {
    // 这里必须提前顶一个textInput,只有这样才可以正常执行ref回调函数
    let textInput = null;
    function click() {
        textInput.focus();
    }
    return (
        <div>
            <input type="text" ref={input => { textInput = input; }} />
            <input type="button" value="选中这个输入框" onClick={click} />
        </div>
    );
}

不要过度使用ref

你的第一个倾向可能是使用refs在你的应用中“make things happen”

如果是这种情况,你必须花一点时间,关键去考虑在组件层次结构中应该拥有什么状态。

通常,在层次结构中处于更高级别的组件“拥有”状态是一个让一切便清除的最适当位置。 有关示例,请参阅本系列的第10篇《提升state》。