下圖是useRef的demo效果圖,經過「一個父組件嵌套一個子組」件來總結一些知識點。react
import React, {
useRef,
useEffect,
useImperativeHandle,
forwardRef,
} from "react";
const RefDemo = () => {
const domRef = useRef(1);
const childRef = useRef(null);
useEffect(() => {
console.log("ref:deom-init", domRef, domRef.current);
console.log("ref:child-init", childRef, childRef.current);
});
const showChild = () => {
console.log("ref:child", childRef, childRef.current);
childRef.current.say();
};
return (
<div style={{ margin: "100px", border: "2px dashed", padding: "20px" }}>
<h2>這是外層組件</h2>
<div
onClick={() => {
console.log("ref:deom", domRef, domRef.current);
domRef.current.focus();
domRef.current.value = 'hh';
}}
>
<label>這是一個dom節點</label><input ref={domRef} />
</div>
<br />
<p onClick={showChild} style={{ marginTop: "20px" }}>
這是子組件
</p>
<div style={{ border: "1px solid", padding: "10px" }}>
<Child ref={childRef} />
</div>
</div>
);
};
export default RefDemo;
複製代碼
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
say: sayHello,
}));
const sayHello = () => {
alert("hello,我是子組件");
};
return <h3>子組件</h3>;
});
等同於 =>
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
say: sayHello,
}));
const sayHello = () => {
alert("hello,我是子組件");
};
return <h3>子組件</h3>;
};
const Child = forwardRef(ChildComponent);
複製代碼