react hooks 父子组件传值
时间: 2023-09-14 12:11:22 浏览: 60
React Hooks中可以使用一些钩子函数来实现父子组件之间的传值。
1. 使用useState钩子函数
通过useState钩子函数可以在父组件中定义一个状态,并将该状态作为props传递给子组件。在子组件中可以通过props获取父组件传递的状态值,并通过回调函数将子组件的值传递给父组件。
父组件:
```
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const [count, setCount] = useState(0);
const handleCallback = (childData) => {
console.log(childData);
};
return (
<div>
<ChildComponent count={count} callback={handleCallback} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default ParentComponent;
```
子组件:
```
import React from 'react';
function ChildComponent(props) {
const handleClick = () => {
props.callback('Hello from child component');
};
return (
<div>
<p>Count: {props.count}</p>
<button onClick={handleClick}>Send Data to Parent</button>
</div>
);
}
export default ChildComponent;
```
2. 使用useContext钩子函数
通过useContext钩子函数可以在父组件中创建一个context对象,并将该对象作为props传递给子组件。在子组件中可以通过useContext获取父组件传递的context对象,并在需要的地方使用该对象的值。
父组件:
```
import React, { createContext, useState } from 'react';
import ChildComponent from './ChildComponent';
export const CountContext = createContext();
function ParentComponent() {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={count}>
<ChildComponent />
<button onClick={() => setCount(count + 1)}>Increment</button>
</CountContext.Provider>
);
}
export default ParentComponent;
```
子组件:
```
import React, { useContext } from 'react';
import { CountContext } from './ParentComponent';
function ChildComponent() {
const count = useContext(CountContext);
return (
<div>
<p>Count: {count}</p>
</div>
);
}
export default ChildComponent;
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)