我正在尝试将多个引用传递给子组件。我尝试将引用作为对象传递,它有效。
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;
如果有更好的方法请建议。预先感谢。
可以使用您提到的方法将多个引用传递给子组件,如果您正在寻找替代方法,一种选择是将引用作为道具单独传递给子组件
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;