作者:2364118915_86406b_479 | 来源:互联网 | 2023-10-17 17:39
1、父组件向子组件传值
父组件向子组件传值一般采用props属性传递
父组件:
import React from "react"
import Child from "./Child"
const dataList = [
{ id: "001", value: "张三" },
{ id: "002", value: "李四" }
]
const Parent = props => {
return (
)
}
export default Parent
子组件:
import React from "react"
const Child = props => {
return (
{
props.dataList.map(item => {item.value})
}
)
}
export default Child
2、子组件向父组件传值
子组件调用父组件传过来的回调函数来更改父组件的state
父组件
import React, { useState } from "react"
import Child from "./Child"
const Parent = props => {
const [count, setCount] = useState(0)
return (
)
}
export default Parent
子组件
import React from "react"
const Child = props => {
return (
{props.count}
)
}
export default Child
3、跨级组件传值(祖孙组件)
context是一个全局变量,像是一个大容器,在任何地方都可以访问到,我们可以把要通信的信息放在context上,然后在其他组件中可以随意取到;
但是React官方不建议使用大量context,尽管他可以减少逐层传递,但是当组件结构复杂的时候,我们并不知道context是从哪里传过来的;而且context是一个全局变量,全局变量正是导致应用走向混乱的罪魁祸首.
父组件
import React, { useState } from "react"
import Child from "./Child"
export const MyCOntext= React.createContext("hello")
const Parent = props => {
return (
)
}
export default Parent
子组件
import React from "react"
import Son from "./Son"
const Child = props => {
return (
)
}
export default Child
孙组件
import React from "react"
import { MyContext } from "./Parent"
export default class Son extends React.Component {
render() {
return (
{
cOntext=> {context}
}
)
}
}
参考:
https://blog.csdn.net/xingfuzhijianxia/article/details/86151243
https://www.cnblogs.com/qinney1109/p/11202085.html
到此这篇关于详解react组件通讯方式的文章就介绍到这了,更多相关react组件通讯内容请搜索编程笔记以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程笔记!