欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > React-组件通信

React-组件通信

2025/4/30 0:13:16 来源:https://blog.csdn.net/qq_40007317/article/details/147493396  浏览:    关键词:React-组件通信

1、父子组件通信

(1)父传子(props 传值)

// 父组件
function App() {const name = '张三'return (<div className="App"><Son name={name} /></div>);
}// 子组件
function Son(props) {return (<div>{ props.name }</div>)
}

(2)子传父(回调函数)

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {console.log(data)setMsg(data)}return (<div className="App"><div>{ msg }</div><Son onGetMsg={getMsg} /></div>);
}// 子组件
function Son({ onGetMsg }) {return (<div><button onClick={() => onGetMsg('子组件给父组件的数据')}>发送数据</button></div>)
}

(3)双向数据绑定

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {console.log(data);setMsg(data)}return (<div className="App"><div>{ msg }</div><Son msg={msg} onGetMsg={getMsg} /></div>);
}// 子组件
function Son({ msg, onGetMsg }) {return (<div><input type="text" value={msg} onChange={(e) => onGetMsg(e.target.value)} /></div>)
}

2、兄弟组件通信

        通过状态提升实现兄弟组件之间传值,子传父 => 父传子

// 父组件
function App() {const [msg, setMsg] = useState('');const getMsg = (data) => {setMsg(data)}return (<div className="App">this is App<A onGetMsg={getMsg} /><B msg={msg} /></div>);
}// 子组件A
function A({ onGetMsg }) {return (<div>this is A component<button onClick={() => onGetMsg('AAA')}>send</button></div>)
}// 子组件B
function B(props) {return (<div>this is B component{ props.msg }</div>)
}

3、跨层级组件通信

  1. 使用createContext创建上下文对象
  2. 在顶层组件(App)中使用Ctx.Provider组件提供数据
  3. 在底层组件(B)中通过useContext获取消费数据
import { createContext, useContext } from 'react';// 1.使用createContext创建上下文对象
const MsgContent = createContext();// 父组件
function App() {const msg = '哈哈哈';return (<div className="App">{/* 2.在顶层组件(App)中使用Ctx.Provider组件提供数据 */}<MsgContent.Provider value={msg}>this is App<A /></MsgContent.Provider></div>);
}// 子组件A
function A() {return (<div>this is A component<B /></div>)
}// 孙子组件B
function B() {// 3.在底层组件(B)中通过useContext获取消费数据const msg = useContext(MsgContent);return (<div>this is B component{msg}</div>)
}

4、任意组件通信(Redux/Zustand)

        见后续文章

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词