React組件傳參方式你了解嗎
序言
眾所周知 ,在業(yè)務(wù)開發(fā)中,無論用的什么框架,首要熟悉的有以下幾點(diǎn):
- 項(xiàng)目搭建,基礎(chǔ)配置,命名規(guī)范。
- 路由配置,配置路由規(guī)則等。
- 組件通信,組件規(guī)范等等。
我們今天要探究的就是React中組件通信的幾種方式,以及各自的應(yīng)用場(chǎng)景。
父子組件通信
在React中,父組件可以通過 props 向子組件傳遞數(shù)據(jù)和回調(diào)函數(shù),從而實(shí)現(xiàn)父子組件之間的通信。同時(shí),子組件可以通過調(diào)用父組件傳遞的回調(diào)函數(shù)來向父組件傳遞數(shù)據(jù)或者觸發(fā)父組件的行為,有以下幾個(gè)注意要點(diǎn)。
- props傳參,傳入數(shù)據(jù)是只讀的。
- 函數(shù)式組件可以直接解構(gòu)用,類組件需要通過this.props.xxxx。
- 子組件數(shù)據(jù)傳父組件時(shí),回調(diào)函數(shù)的返回值就是傳的參。
// ParentComponent.js import React, { useState } from 'react'; import ChildComponent from './ChildComponent'; ? function ParentComponent() { const [messageFromChild, setMessageFromChild] = useState(''); ? const handleMessageFromChild = (message) => { setMessageFromChild(message); }; ? return ( <div> <h1>Parent Component</h1> <p>Message from Child: {messageFromChild}</p> <ChildComponent giveChildren={parentData} onMessage={handleMessageFromChild} /> </div> ); } ? export default ParentComponent;
// ChildComponent.js ? //1.函數(shù)式組件 ? import React from 'react'; ? function ChildComponent(props) { const { onMessage , parentData } = props; const sendMessageToParent = () => { onMessage('Hello from Child!'); }; ? return ( <div> <h2>Child Component</h2> <h2>{ parentData }</h2> <button onClick={sendMessageToParent}>Send Message to Parent</button> </div> ); } ? export default ChildComponent; ? //1. 類組件 ? import React, { Component } from 'react' ? export default class ChildComponent extends Component { render() { return ( <div> {this.props.parentToChild} </div> ) } }
小結(jié):我們看上面代碼,通過在組件上屬性名,在子組件中,就可以從props中解構(gòu)出該屬性,這個(gè)屬性也可以是一個(gè)回調(diào)函數(shù),當(dāng)該回調(diào)函數(shù)調(diào)用時(shí),入?yún)⒕蜁?huì)在父組件的形參那里拿到,跟jsonp的原理一樣。
父孫組件通信
聰明的同學(xué)相信可以通過父子組件通信舉一反三,但是為了一個(gè)傳參,寫好幾層回調(diào),這種代碼看起來就不適用,所以為了解決這個(gè)問題,react 給我們提供了一個(gè)方法 createContext 這是一個(gè)創(chuàng)建React 上下文的函數(shù),這個(gè)上下文提供了組件中共享值的方法,不用顯示的通過props層層傳遞。
//跨組件通信 import React, { Component } from 'react' //創(chuàng)建context 給初始值 const UserMessage = React.createContext({ nickName: 'yyy', level: 1 }) ? export default class TextSingal extends Component { constructor(props) { super(props) this.state = { nickName: 'kkk', level: 99, name: 'ppp', age: 9999 } } render() { const { name, age } = this.state return ( <div> <h2>爺爺組件</h2> <h3>name:{name}</h3> <h3>age:{age}</h3> {/* 改變數(shù)據(jù)孫組件也更新 */} <button onClick={() => this.handelClick()}>updated</button> {/* 傳入state對(duì)象和foo回調(diào)函數(shù) */} {/* foo函數(shù)用于孫組件和爺組件通信 */} <UserMessage.Provider value={{ ...this.state, foo: (name, age) => this.updateDatas(name, age) }}> <Father /> </UserMessage.Provider> ? </div> ) } handelClick() { this.setState({ nickName: '虎威神', level: 9999 }) } updateDatas(name, age) { this.setState({ name, age }) } } ? class Father extends Component { render() { return ( <div> <h2>爸爸組件</h2> <Son /> </div> ) } } class Son extends Component { render() { // 解構(gòu) const { nickName, level, foo } = this.context return ( <div> <h2>兒子組件</h2> <h3>nickname:{nickName}</h3> <h3>level:{level}</h3> {/* 下面兩種調(diào)用方式都可以 */} {/* 改變爺組件的數(shù)據(jù) */} <button onClick={() => this.handelClick()}>updated</button> <button onClick={() => foo('牛霸天', 18)}>updated</button> </div> ) } handelClick() { this.context.foo('牛霸天', 18) } } // 接受爺組件傳遞的值 Son.contextType = UserMessage
小結(jié):通過上述我們創(chuàng)建了一個(gè)context,然后用context.provider 將組件包裹,那么被包裹的組件將會(huì)共享這個(gè)context,在context上定義回調(diào),在孫組件通過 this.context 即可調(diào)用回調(diào),或者使用傳入數(shù)據(jù)。
兄弟組件通信
相對(duì)于Vue中兄弟組件傳參,react會(huì)相對(duì)原始一些,Vue中可以通過evenbus,便捷的在各種組件中傳遞參數(shù)。而react的做法是,在兄弟組件共同的父組件中,創(chuàng)建一個(gè)公用的state,然后兄弟A組件通過跟父組件傳遞傳參改變這個(gè)state,父組件將新值也傳給B組件,以達(dá)到兄弟組件傳參的目的。
父組件
//父組件 import React, {Component} from "react" import Abrother from './Abrother' import Bbrother from './Bbrother' ? export default class common extends Component { // 公共的組件部分 state = { inputValue:'' } ? handleUpdate = (inputValue) => { this.setState({ inputValue }) } ? render(){ return( <> <Abrother sendFn={this.handleUpdate}/> <Bbrother sendValue={this.state.inputValue}/> </> ) } }
兄弟A
import React,{Component} from "react"; ? export default class Abrother extends Component { ? // 兄弟組件A需要將值先傳給一個(gè)公共的父組件 state = { inputValue:'' } ? handleChange = (e)=>{ console.log(e.target.value); this.setState({ inputValue:e.target.value }) } handleSend = () => { const {sendFn} = this.props; sendFn(this.state.inputValue) } ? render(){ return( <> <div> <span>A組件</span> <input type='text' value={this.state.inputValue} onChange={this.handleChange}></input> <button onClick={this.handleSend}>發(fā)送A組件的值</button> </div> </> ) } }
兄弟B
import React, {Component} from "react" ? export default class Bbrother extends Component { ? ? render(){ const { sendValue} = this.props; return ( <div> <span>b組件</span> <h1>{ sendValue }</h1> </div> ) } }
小結(jié): 組件A,想要將輸入框中的值傳給組件B,那么先在父組件的 state 中定義一個(gè)變量,這個(gè)變量就是要傳給組件 B 中的值,父組件中將這個(gè)值通過props的形式傳入b組件。接下來定義父組件和A組件中的回調(diào)函數(shù)觸發(fā),當(dāng)A組件數(shù)據(jù)移動(dòng),調(diào)用回調(diào)函數(shù),改變父組件 state 中的值,以達(dá)到將新值傳給B組件的目的。
跨組件通信
props ,當(dāng)組件層級(jí)連貫且淺的時(shí)候,可以直接使用props進(jìn)行通信。
context API , 當(dāng)組件數(shù)據(jù)跨越了層級(jí)的時(shí)候,可以用此方法省去層層props。
事件總線,evenbus等。通過引入庫(kù)或者自己手寫一個(gè)簡(jiǎn)單的,進(jìn)行通信。
使用 Redux MobX,對(duì)于非常復(fù)雜的組件中共享狀態(tài)的數(shù)據(jù)處理時(shí),可以用這兩個(gè)庫(kù)進(jìn)行處理
使用 Refs,直接操作DOM 元素,或者組件實(shí)例。
到此這篇關(guān)于React組件傳參方式你了解嗎的文章就介紹到這了,更多相關(guān)React組件傳參內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過濾器
這篇文章主要介紹了如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過濾器,在vue及react中經(jīng)常會(huì)遇到,今天通過實(shí)例代碼給大家講解,需要的朋友可以參考下2018-11-11react?hooks頁(yè)面實(shí)時(shí)刷新方式(setInterval)
這篇文章主要介紹了react?hooks頁(yè)面實(shí)時(shí)刷新方式(setInterval),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03在react項(xiàng)目中webpack使用mock數(shù)據(jù)的操作方法
這篇文章主要介紹了在react項(xiàng)目中webpack使用mock數(shù)據(jù)的操作方法,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06react中使用js實(shí)現(xiàn)頁(yè)面滾動(dòng)監(jiān)聽(推薦)
這篇文章主要介紹了react中使用js實(shí)現(xiàn)頁(yè)面滾動(dòng)監(jiān)聽,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04解決React報(bào)錯(cuò)Expected?`onClick`?listener?to?be?a?function
這篇文章主要為大家介紹了React報(bào)錯(cuò)Expected?`onClick`?listener?to?be?a?function解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12