平顶山做网站优化,互联网技术的特点,如何使用wordpress制作网站,自建的电子网站如何做推广组件通信
概念#xff1a;组件通信就是组件之间的数据传递#xff0c;根据组件嵌套关系的不同#xff0c;有不同的通信方法 父传子
基础实现 实现步骤#xff1a;
1.父组件传递数据-在子组件标签上绑定属性 2.子组件接收数据-子组件通过props参数接收数据 props说明
1.…组件通信
概念组件通信就是组件之间的数据传递根据组件嵌套关系的不同有不同的通信方法 父传子
基础实现 实现步骤
1.父组件传递数据-在子组件标签上绑定属性 2.子组件接收数据-子组件通过props参数接收数据 props说明
1.props可传递任意的数据
数字、字符串、布尔值、数组、对象、函数、JSX 2.props是只读对象
子组件只能读取props中的数据不能直接进行修改父组件的数据只能由父组件修改
特殊的prop children
场景当我们把内容嵌套在子组件标签中时父组件会自动在名为children的prop属性中接收该内容 子传父 核心思路在子组件中调用父组件中的函数并传递参数 使用状态提升实现兄弟组件通信 实现思路借助“状态提升”机制通过父组件进行兄弟组件之间的数据传递
1.A组件先通过子传父的方式把数据传给父组件App
2.App拿到数据后通过父传子的方式再传递给B组件
//项目的根组件
//App - index.js - public/index.html(root)
import {useState} from reactfunction A({onGetAName}){//Son组件中的数据const namethis is A namereturn(divthis is A compnent,button onClick{()onGetAName(name)}send/button/div)
}function B({name}){return(divthis is B compnent,{name}/div)
}function App() {const [name,setName]useState()const getAName(name){setName(name)}return (divthis is AppA onGetAName{getAName}/B name{name}//div);
}export default App;
使用Context机制跨层级组件通信 实现步骤
1.使用createContext方法创建一个上下文对象Ctx
2.在顶层组件App中通过Ctx.Provider组件提供数据
3.在底层组件B中通过useContext钩子函数获取消费数据
//App-A-Bimport { createContext, useContext } from react;//1.createContext方法创建一个上下文对象const MsgContextcreateContext()//2.在顶层组件通过Provider组件提供数据
//3.在底层组件通过useContext钩子函数使用数据
function A(){return(divthis is A compnentB //div)
}function B(){const msguseContext(MsgContext)return(divthis is B compnent,{msg}/div)
}function App() {const msgthis is app msgreturn (divMsgContext.Provider value{msg}this is AppA //MsgContext.Provider/div);
}export default App;
只要形成一个顶层和底层的嵌套关系就可以使用这套机制