React的ref是啥强力一波

21次阅读

共计 1259 个字符,预计需要花费 4 分钟才能阅读完成。

React ref

理解:通过指定 ref 获得你想操作的元素,然后进行修改

string 使用方法

<input ref=”myInput” />

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

ref 作为回调函数的方式去使用

class Input extends Component {constructor(props){super(props);
    }
    
    focus = () => {this.textInput.focus();
    }
    
    render(){
        return (
            <div>
                <input ref={(input) => {this.textInput = input}} />
            </div>
        )
    }
}

input 参数是哪来的

回调函数将接收当前的 DOM 元素作为参数,然后存储一个指向这个 DOM 元素的引用。那么在示例代码中,我们已经把 input 元素存储在了 this.textInput 中,在 focus 函数中直接使用原生 DOM API 实现 focus 聚焦。

回调函数什么时候被调用

答案是当组件挂载后和卸载后,以及 ref 属性本身发生变化时,回调函数就会被调用。

不能在无状态组件中使用 ref

原因很简单,因为 ref 引用的是组件的实例,而无状态组件准确的说是个函数组件 (Functional Component),没有实例。

理解:class 组件 - 对象组件 - 有实例 无状态组件 - 函数组件 - 无实例

上代码:

function MyFunctionalComponent() {return <input />;}

class Parent extends React.Component {render() {
        return (
            <MyFunctionalComponent
                ref={(input) => {this.textInput = input;}} />
        );
    }
}

父组件的 ref 回调函数可以使用子组件的 DOM。

function CustomTextInput(props) {
    return (
        <div>
            <input ref={props.inputRef} />
        </div>
    );
}

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

原理就是父组件把 ref 的回调函数当做 inputRefprops 传递给子组件,然后子组件 <CustomTextInput> 把这个函数和当前的 DOM 绑定,最终的结果是父组件 <Parent> 的 this.inputElement 存储的 DOM 是子组件 <CustomTextInput> 中的 input。
同样的道理,如果 A 组件是 B 组件的父组件,B 组件是 C 组件的父组件,那么可用上面的方法,让 A 组件拿到 C 组件的 DOM。

理念

Facebook 非常不推荐会打破组件的封装性的做法,多级调用确实不雅,需要考虑其他更好的方案去优化

正文完
 0