1

我有一个父组件,它有一个带有 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>
  )
);
4

2 回答 2

3

您在这里错误地使用了 refs。forwardRefref被传递给组件时工作。除此之外的任何东西都是组件的道具。因此,在您的情况下,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>
    </>
  );
};

在此处检查此代码框。

于 2020-10-28T20:04:36.547 回答
0

你也可以像这样绑定道具:

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>

或codeandbox链接直接查看它的作用:

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

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

于 2020-10-28T20:04:24.427 回答