做服装的外贸网站,纯静态网站模板,网站推广名片,湖南省第四工程公司官网(创作不易#xff0c;感谢有你#xff0c;你的支持#xff0c;就是我前行的最大动力#xff0c;如果看完对你有帮助#xff0c;请留下您的足迹#xff09;
目录
受控表单绑定
React中获取DOM
组件通信
父传子
父传子-基础实现
父传子-props说明
父传子 - 特殊的…(创作不易感谢有你你的支持就是我前行的最大动力如果看完对你有帮助请留下您的足迹
目录
受控表单绑定
React中获取DOM
组件通信
父传子
父传子-基础实现
父传子-props说明
父传子 - 特殊的prop children
子传父
使用状态提升实现兄弟组件通信
使用Context机制跨层级组件通信 受控表单绑定 概念使用React组件的状态useState控制表单的状态 1. 准备一个React状态值 2. 通过value属性绑定状态通过onChange属性绑定状态同步的函数 //受控绑定表单
import { useState } from reactfunction App() {const[value ,setValue]useState()return (divinput value{value}onChange{(e)setValue(e.target.value)}typetext//div);
}export default App;
React中获取DOM 在 React 组件中获取/操作 DOM需要使用 useRef React Hook钩子函数 分为两步 1. 使用useRef创建 ref 对象并与 JSX 绑定 2. 在DOM可用时通过 inputRef. current 拿到 DOM 对象 2 //React获取DOM
import { useRef } from reactfunction App() {const inputRef useRef(null)const showDom(){console.log(inputRef.current)}return (divinput typetext ref{inputRef}/button onClick{showDom}获取dom/button/div);
}export default App;
组件通信 概念组件通信就是 组件之间的数据传递 根据组件嵌套关系的不同有不同的通信方法 4 父传子
父传子-基础实现 实现步骤 1. 父组件传递数据 - 在子组件标签上 绑定属性 2. 子组件接收数据 - 子组件通过 props参数 接收数据 //父传子
function Son(props) {return divthis is son,{props.name}/div
}function App() {const name this is app namereturn (divSon name{name} //div);
}export default App;网页显示为
父传子-props说明 1. props可传递任意的数据 数字、字符串、布尔值、数组、对象、函数、JSX 2. props是只读对象 子组件 只能读取props中的数据 不能直接进行修改, 父组件的数据只能由父组件修改 父传子 - 特殊的prop children 场景当我们把内容嵌套在子组件标签中时父组件会自动在名为children的prop属性中接收该内容 子传父 核心思路在子组件中调用父组件中的函数并传递参数 function Son({onGetSonMsg}) {const sonMsgthis is son msgreturn (divthis is Sonbutton onClick{()onGetSonMsg(sonMsg)}sendMsg /button/div)
}function App() {const getMsg(msg){console.log(msg)}return (divthis is APPSon onGetSonMsg{getMsg} //div);
}export default App;使用状态提升实现兄弟组件通信 实现思路借助“状态提升”机制通过父组件进行兄弟组件之间的数据传递 1. A组件先通过子传父的方式把数据传给父组件App 2. App拿到数据后通过父传子的方式再传递给B组件 // 1. 通过子传父 A - App
// 2. 通过父传子 App - Bimport { useState } from reactfunction A ({ onGetAName }) {// Son组件中的数据const name this 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) {console.log(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 MsgContext createContext()// 2. 在顶层组件 通过Provider组件提供数据// 3. 在底层组件 通过useContext钩子函数使用数据function A () {return (divthis is A componentB //div)
}function B () {const msg useContext(MsgContext)return (divthis is B compnent,{msg}/div)
}function App () {const msg this is app msgreturn (divMsgContext.Provider value{msg}this is AppA //MsgContext.Provider/div)
}export default App