我在应用程序中使用usepperativeHang Hook来访问propart falue parent component:
const [phone,setPhone]=useState("");
useImperativeHandle(
ref,
() => ({
type: "text",
name: "phone",
value: phone
}),
[phone]
);
当我使用setphone更新手机时,值不会更新。我的实施有什么问题?
usepperativeHandle需要让组件使用forwardRef
,一旦这样做,您将能够访问父母的更新ref,因为您将phone
作为其依赖关系。
import React, {
useEffect,
useState,
useImperativeHandle,
forwardRef,
useRef
} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const App = forwardRef((props, ref) => {
const [phone, setPhone] = useState("");
useImperativeHandle(
ref,
() => ({
type: "text",
name: "phone",
value: phone
}),
[phone]
);
useEffect(() => {
setTimeout(() => {
setPhone("9898098909");
}, 3000);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
});
const Parent = () => {
const appRef = useRef(null);
const handleClick = () => {
console.log(appRef.current.value);
};
return (
<>
<App ref={appRef} />
<button onClick={handleClick}>Click</button>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);
工作演示
如果您懒惰并且/或优化在您的应用程序中并不重要,则可以将[{}]
的依赖关系传递给useImperativeHandle()
,以更新组件重新租赁时,以确保值始终是最新的。
const App = forwardRef((props, ref) => {
const [phone, setPhone] = useState("");
useImperativeHandle(
ref,
() => ({
type: "text",
name: "phone",
value: phone,
// other values that you don't have to keep track of via dependency list
}),
[{}]
);