我在我的应用程序中使用useImperativeHandle钩子来访问父组件的值:
const [phone,setPhone]=useState("");
useImperativeHandle(
ref,
() => ({
type: "text",
name: "phone",
value: phone
}),
[phone]
);
当我使用setPhone更新手机时,值将不会被更新。我的执行有什么问题?
发布于 2019-05-27 06:46:22
useImperativeHandle需要让组件使用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);
发布于 2021-03-31 16:12:02
如果您懒惰和/或优化在您的应用程序中还不是非常重要,您可以将[{}]
的依赖项传递给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
}),
[{}]
);
https://stackoverflow.com/questions/56311759
复制相似问题