创建 Refs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
// 访问 Refs
const node = this.myRef.current;
访问 Refs
当 ref 被传递给 render 中的元素时,对该节点的引用可以在 ref 的 current 属性中被访问。
函数组件的 ref
import React, { useRef } from 'react'
const CustomTextInput = (props) => {
/* 这里必须声明 textInput,这样 ref 才可以引用它 */
const textInput = useRef(null);
const handleClick() {
textInput.current.focus();
}
return (
<div>
<input type="text" ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
React 会在组件挂载时给 current 属性传入 DOM 元素,并在组件卸载时传入 null 值。ref 会在 componentDidMount 或 componentDidUpdate 生命周期钩子触发前更新。于是在函数组件中,我们可以用 ref 来模拟 componentDidUpdate 这个生命周期
import { useEffect, useRef } from 'react';
const useDidUpdate = (f, conditions) => {
const didMountRef = useRef(false);
useEffect(() => {
if (!didMountRef.current) {
didMountRef.current = true;
return;
}
return f && f();
}, conditions);
};
export default useDidUpdate;