在reactjs中将超过ref传递给子组件?

问题描述 投票:0回答:1

我正在尝试将多个引用传递给子组件。我尝试将引用作为对象传递,它有效。

import React from "react";

// Parent component
function App() {
  const inputRef = React.useRef();
  const btnRef = React.useRef();

  return (
    <div>
      <input ref={inputRef} />
      <button ref={btnRef}>click me</button>
      <ChildComponent ref={{ inputRef, btnRef }} />
    </div>
  );
}

// Child component
const ChildComponent = React.forwardRef((props, ref) => {
  /**
   * console.log ref -> {inputRef: {…}, btnRef: {…}}
   */

  return (
    <>This is Child Component</>
  );
});

export default App;

如果有更好的方法请建议。预先感谢。

javascript reactjs object react-hooks
1个回答
0
投票

可以使用您提到的方法将多个引用传递给子组件,如果您正在寻找替代方法,一种选择是将引用作为道具单独传递给子组件

import React from "react";
// Parent component
function App() {
  const inputRef = React.useRef();
  const btnRef = React.useRef();

  return (
    <div>
      <input ref={inputRef} />
      <button ref={btnRef}>click me</button>
      <ChildComponent inputRef={inputRef} btnRef={btnRef} />
    </div>
  );
}

// Child component
const ChildComponent = React.forwardRef(({ inputRef, btnRef }, ref) => {
  /**
   * You can use inputRef and btnRef directly here
   */

  return (
    <>This is Child Component</>
  );
});

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.