如何在 React Hooks 的父级中单击按钮时将焦点设置在子组件的输入上

How to set focus on child component's input on a button click in the parent in React Hooks

我有一个父组件,它有一个带有 onClick 事件的按钮,当出现错误时,我想关注子组件中的输入。我知道这可以使用 useRef 来完成,但我一直收到未定义的错误。这是我的代码:

/* Parent Component */
const parent = () => {
  const acresRef = useRef();
  const addrRef = useRef();

  const acresFocus = () => {
    acresRef.current.focus();
  };

  const addressFocus = () => {
    addrRef.current.focus();
  };

  return (
    <Child addrRef={addrRef} acresRef={acresRef} />
    <button onClick={acresFocus} />
    <button onCLick={addressFocus} />
  )
}

/*Child Component*/
const Child = forwardRef(
  ({props}, acresRef, addrRef) => (
  <div>
    <label for="address">Address</label>
    <input type="text" name="address" ref={addrRef} />
  </div>
  <div>
    <label for="acres">Acres</label>
    <input type="text" name="acres" ref={acresRef} />
  </div>
  )
);

您也可以像这样绑定 props :

const Child = (props) => {
  const onClick = props.onClick;
  return(<div><p>
  {onClick()}
  </p>
  </div>
  );
}

/* Parent Component */
const ParentEl = () => {
  const onClick = ()=>{return "hi"};

  return (
    <div>
      <Child onClick={onClick} />
    </div>
  )
}

/*Child Component*/


export default function App() {
  return (
    <div className="App">
      <ParentEl />
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

或 codesandbox link 直接查看它的作用:

https://codesandbox.io/s/hidden-water-s8qjj?file=/src/App.js

这里: const onClick = props.onClick; 在子组件中做所有的魔法

您在这里错误地使用了 refs。 forwardRefref 传递给组件时有效。除此之外的任何东西都是组件的道具。因此,在您的情况下,子组件将在 props 中接收 acresRefaddrRef

/*Child Component*/
const Child = (props) => (
  <>
    <div>
      <label htmlFor="address">Address</label>
      <input type="text" name="address" ref={props.addrRef} />
    </div>
    <div>
      <label htmlFor="acres">Acres</label>
      <input type="text" name="acres" ref={props.acresRef} />
    </div>
  </>
);

/* Parent Component */
const Parent = () => {
  const acresRef = React.useRef();
  const addrRef = React.useRef();

  const acresFocus = () => {
    acresRef.current.focus();
  };

  const addressFocus = () => {
    addrRef.current.focus();
  };

  return (
    <>
      <Child addrRef={addrRef} acresRef={acresRef} />
      <button onClick={acresFocus}>acres</button>
      <button onClick={addressFocus}>address</button>
    </>
  );
};

检查此 codesandbox here