前端react入门day03-react获取dom与组件通信
(创作不易,感谢有你,你的支持,就是我前行的最大动力,如果看完对你有帮助,请留下您的足迹)
目录
受控表单绑定
React中获取DOM
组件通信
父传子
父传子-基础实现
父传子-props说明
父传子 – 特殊的prop children
子传父
使用状态提升实现兄弟组件通信
使用Context机制跨层级组件通信
受控表单绑定
概念:使用React组件的状态(useState)控制表单的状态
1. 准备一个React状态值
![]()
2. 通过value属性绑定状态,通过onChange属性绑定状态同步的函数
![]()
//受控绑定表单
import { useState } from "react"
function App() {
const[value ,setValue]=useState('')
return (
setValue(e.target.value)}
type="text"/>
);
}
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 "react"
function App() {
const inputRef = useRef(null)
const showDom=()=>{
console.log(inputRef.current)
}
return (
);
}
export default App;
组件通信
概念:组件通信就是
组件之间的数据传递,
根据组件嵌套关系的不同,有不同的通信方法4
父传子
父传子-基础实现
实现步骤
1. 父组件传递数据 – 在子组件标签上
绑定属性2. 子组件接收数据 – 子组件通过
props参数
接收数据
//父传子
function Son(props) {
return this is son,{props.name}
}
function App() {
const name = 'this is app name'
return (
);
}
export default App;
网页显示为:
父传子-props说明
1. props可传递任意的数据
数字、字符串、布尔值、数组、对象、函数、JSX
![]()
![]()
2. props是只读对象
子组件
只能读取props中的数据
,不能直接进行修改, 父组件的数据只能由父组件修改
父传子 – 特殊的prop children
场景:当我们把内容嵌套在子组件标签中时,父组件会自动在名为children的prop属性中接收该内容
![]()
子传父
核心思路:在子组件中调用父组件中的函数并传递参数
![]()
![]()
function Son({onGetSonMsg}) {
const sonMsg="this is son msg"
return (
this is Son
)
}
function App() {
const getMsg=(msg)=>{
console.log(msg)
}
return (
this is APP
);
}
export default App;
使用状态提升实现兄弟组件通信
实现思路:借助“状态提升”机制,通过父组件进行兄弟组件之间的数据传递
1. A组件先通过子传父的方式把数据传给父组件App
2. App拿到数据后通过父传子的方式再传递给B组件
// 1. 通过子传父 A -> App
// 2. 通过父传子 App -> B
import { useState } from "react"
function A ({ onGetAName }) {
// Son组件中的数据
const name = 'this is A name'
return (
this is A compnent,
)
}
function B ({ name }) {
return (
this is B compnent,
{name}
)
}
function App () {
const [name, setName] = useState('')
const getAName = (name) => {
console.log(name)
setName(name)
}
return (
this is App
)
}
export default App
使用Context机制跨层级组件通信
实现步骤:
1. 使用createContext方法创建一个上下文对象Ctx
2. 在顶层组件(App)中通过
Ctx.Provider 组件
提供数据3. 在底层组件(B)中通过
useContext
钩子函数获取消费数据
// App -> A -> B
import { createContext, useContext } from "react"
// 1. createContext方法创建一个上下文对象
const MsgContext = createContext()
// 2. 在顶层组件 通过Provider组件提供数据
// 3. 在底层组件 通过useContext钩子函数使用数据
function A () {
return (
this is A component
)
}
function B () {
const msg = useContext(MsgContext)
return (
this is B compnent,{msg}
)
}
function App () {
const msg = 'this is app msg'
return (
this is App
)
}
export default App
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/57053ea4bc.html







