如何使用useRef钩子函数从父组件内部调用子组件中的函数
在ReactJS中,我们可以将函数引用从父组件传递给子组件。但是,在某些情况下,您可能需要从父组件内部调用子组件中的函数。在本文中,我们将探讨如何在ReactJS中实现这一点。
从父组件内部调用子组件中的函数的方法
以下是从父组件内部调用子组件中的函数的步骤:
- 在父组件中,创建一个useRef钩子。
- 将此引用作为props传递给子组件。
- 在子组件中使用该引用,以便在需要的时候调用函数。
示例
- 在此示例中,父组件使用useRef钩子和useState函数将引用作为props传递给子组件。将此引用分配给子组件中的按钮,该按钮将通过CSS属性display-none隐藏。
- 在子组件中,有一个输入字段和一个状态变量。通过输入字段的onChange函数将状态变量设置为输入值。
- 通过单击子组件中的按钮,它将设置父组件中的状态变量。
- 父组件中有一个按钮。在这里,我们尝试使用ref从父组件中以编程方式单击子组件中的按钮。
- 当我们在父组件中点击按钮时,它将调用子组件的onclick函数并设置父组件的状态变量。
创建React应用程序
步骤1: 使用以下命令创建一个React应用程序。
npx create-react-app foldername
步骤2: 创建完您的项目文件夹,如文件夹名称,请使用以下命令切换到该文件夹:
cd foldername
项目结构: 看起来会像下面这样。
文件路径 – src/App.js:
import './App.css';
import Parent from './Parent';
function App() {
return (
<div>
{/*Rendering the Parent component */}
<Parent />
</div>
);
}
export default App;
文件路径 – src / Parent.js:
import { useRef, useState } from 'react';
import Child from './Child';
function Parent() {
const [name, setname] = useState("");
const childref = useRef();
return (
<div style={{margin:"20px"}}>
<div>Parent Component</div>
{/* Displayed name which was written in
child component input field*/}
{name !== '' && <div>{name}</div>}
{/* By clicking on this button, the onclick
method will click the button in the child
component using useRef hook*/}
<button onClick={() => { childref.current.click() }}
style={{ margin: "2px" }}>
Display name
</button>
{/* Rendering the child component */}
<Child reference={childref} setname={setname} />
</div>
)
}
export default Parent;
文件路径 – src/Child.js:
import { useState } from 'react';
function Child(props) {
const [input, setinput] = useState("");
return (
<div style={{ marginTop: "30px" }}>
<div>Child Component</div>
{/*The input onchange function will set
the input state variable*/}
<input type="text" onChange=
{(e) => { setinput(e.target.value) }}>
</input>
{/* This has reference which is
sent by Parent as props*/}
<button ref={props.reference}
style={{ display: "none" }}
onClick={() => { props.setname(input) }} >
</button>
</div>
)
}
export default Child;
输出: