useImperativeHandle 钩子不更新值

Had*_*bar 2 reactjs react-hooks

我在我的应用程序中使用 useImperativeHandle 钩子来访问父组件的值:

const [phone,setPhone]=useState("");
 useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
Run Code Online (Sandbox Code Playgroud)

当我使用 setPhone 更新手机时,值不会更新。我的实现有什么问题?

Shu*_*tri 5

useImperativeHandle 需要让组件 use 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);
Run Code Online (Sandbox Code Playgroud)

工作演示