網站首頁 編程語言 正文
組件通信
組件間是相互隔離的,若需要用到外部組件數據,就必須使用組件間通信來傳輸數據
-
組件通信方法
-
父組件-->子組件
-
父組件提供要傳遞的 state 數據
-
給子組件標簽添加屬性,值就是 state 數據
-
子組件使用 props 進行數據的接收
-
class Parent extends React.Component{
state = {
name : 'Jack'
}
render() {
return (
<div>
<App name={this.state.name}/>
</div>
)
}
}
// 子組件使用 props 接收數據
-
子組件--> 父組件
思路:父組件提供一個回調函數,子組件調用,將要傳遞的數據作為回調函數的參數傳遞到父組件
-
父組件提供回調函數
-
將回調函數作為屬性值,傳遞給子組件
-
子組件通過 props 調用回調函數
-
將子組件要傳遞的數據作為參數傳遞給回調函數
-
// 父組件傳遞數據
class Parent extends React.Component{
state = {
message : ''
}
getChild = (msg) => {
this.setState({
message : msg
})
}
render() {
return (
<div>
<Child getMsg={this.getChild}/>
<h1>{this.state.message}</h1>
</div>
)
}
}
// 子組件使用 props 接收數據
class Child extends React.Component{
state = { name : 'Tom'}
handleClick = () => {
this.props.getMsg(this.state.name)
}
render() {
return (
<button onClick={this.handleClick}>點我傳送數據</button>
)
}
}
-
兄弟組件之間
將數據傳送到最近的公共父組件中,然后由公共父組件進行管理
需要通信的子組件使用 props 接收狀態或操作狀態
// 公共父組件 class Parent extends React.Component{ // 狀態共享 state = { count : 0 } // 修改數據 onChange = () => { this.setState({ count : this.state.count + 1 }) } render() { return ( <div> <Child1 count = {this.state.count} /> <Child2 onChange = {this.onChange}/> </div> ) } } const Child1 = props => { return <h1>計數器:{props.count}</h1> } const Child2 = props => { return <button onClick={() => props.onChange()}>+1</button> } ReactDOM.render(<Parent />, document.getElementById('root'))
-
跨組件通信
-
調用 React.createContext() 創建 Provider (提供數據) 和 Consumer(消費數據) 兩個組件
-
使用 Provider 組件作為父節點
-
在 Provider 組件中設置一個 value 屬性,表示需要傳輸的數據
-
<Provider value="xxx">
...
</Provider>
-
調用 Consumer 組件接收數據
<Consumer> {data => <h1>{data}</h1>} </Consumer>
原文鏈接:https://blog.csdn.net/weixin_51642358/article/details/126375542
- 上一篇:React中Props的使用
- 下一篇:淺談Redis6.x io事件驅動模型
相關推薦
- 2022-10-05 nginx配置指令之server_name的具體使用_nginx
- 2022-06-01 Android實現拍照或者選取本地圖片_Android
- 2022-10-26 Google?Kubernetes?Engine?集群實戰詳解_云其它
- 2022-10-07 Rust中的Struct使用示例詳解_相關技巧
- 2023-01-11 解決?Redis?數據傾斜、熱點等問題_Redis
- 2022-10-28 react如何向數組中追加值_React
- 2023-03-15 Android?flutter?Dio鎖的巧妙實現方法示例_Android
- 2022-07-23 Python代碼實現雙鏈表_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支