react元件通訊

2022-07-09 05:30:14 字數 3139 閱讀 9751

元件是封閉的,要接收外部資料應該通過 props 來實現

 props的作用:接收傳遞給元件的資料

 傳遞資料:給元件標籤新增屬性

 接收資料:函式元件通過引數props接收資料,類元件通過 this.props 接收資料

function hello(props) )}

class hello extends react.component )}

}//''是字串形式,傳遞的是number型

特點:

可以給元件傳遞任意型別的資料 //陣列,物件,函式,jsx元件等都可以

props 是唯讀的物件,只能讀取屬性的值,無法修改物件

注意:使用類元件時,如果寫了建構函式,應該將 props 傳遞給 super(),否則,無法在建構函式中獲取到 props!

class hello extends react.component 

render()

}}

父元件提供要傳遞的state資料

給子元件標籤新增屬性,值為 state 中的資料

子元件中通過 props 接收父元件中傳遞的資料

class parent extends react.component 

render()

}function child(props)

}

思路:利用**函式,父元件提供**,子元件呼叫,將要傳遞的資料作為**函式的引數。

父元件提供乙個**函式(用於接收資料)

將該函式作為屬性的值,傳遞給子元件

子元件通過 props 呼叫**函式

將子元件的資料作為引數傳遞給**函式

class parent extends react.component 

render()

}class child extends react.component

handleclick = () =>

return (

點我,給父元件傳遞資料

)}

將共享狀態提公升到最近的公共父元件中,由公共父元件管理這個狀態

 思想:狀態提公升

 公共父元件職責:1. 提供共享狀態 2. 提供操作共享狀態的方法

 要通訊的子元件只需通過 props 接收狀態或操作狀態的方法

// 父元件

class counter extends react.component

// 提供修改狀態的方法

onincrement = () => )

}render()

}const child1 = props =>

const child2 = props => >+1

}reactdom.render(, document.getelementbyid('root'))

作用:跨元件傳遞資料(比如:主題、語言等) //相隔多個元件之間傳遞資料

呼叫 react. createcontext() 建立 provider(提供資料) 和 consumer(消費資料) 兩個元件。

使用 provider 元件作為父節點。

設定 value 屬性,表示要傳遞的資料。

呼叫 consumer 元件接收資料。

// 建立context得到兩個元件

const = react.createcontext()

render()

}const subnode = props =>

const child = props => } //>data引數表示接收到的資料

)}

1 children 屬性

children 屬性:表示元件標籤的子節點。當元件標籤有子節點時,props 就會有該屬性

children 屬性與普通的props一樣,值可以是任意值(文字、react元素、元件,甚至是函式)

function hello(props) )}

我是子節點

2 props 校驗

對於元件來說,props 是外來的,無法保證元件使用者傳入什麼格式的資料

 如果傳入的資料格式不對,可能會導致元件內部報錯

 關鍵問題:元件的使用者不知道明確的錯誤原因

props 校驗:允許在建立元件的時候,就指定 props 的型別、格式等

 作用:捕獲使用元件時因為props導致的錯誤,給出明確的錯誤提示,增加元件的健壯性

1. 安裝包 prop-types (yarn add prop-types / npm i props-types)

2. 匯入 prop-types 包

3. 使用元件名.proptypes = {} 來給元件的props新增校驗規則

4. 校驗規則通過 proptypes 物件來指定

import proptypes from 'prop-types'

return ()}

// 約定colors屬性為array型別

// 如果型別不對,則報出明確錯誤,便於分析錯誤原因

colors: proptypes.array

}約束規則

1. 常見型別:array、bool、func、number、object、string

2. react元素型別:element

3. 必填項:isrequired

4. 特定結構的物件:shape()

// 常見型別

optionalfunc: proptypes.func,

// 必選

requiredfunc: proptypes.func.isrequired,

// 特定結構的物件

optionalobjectwithshape: proptypes.shape()

3 props 的預設值

場景:分頁元件  每頁顯示條數

 作用:給 props 設定預設值,在未傳入 props 時生效

return (

此處展示props的預設值:)}

// 設定預設值

pagesize: 10

}// 不傳入pagesize屬性

react 元件通訊

父元件通過props向子元件傳遞需要的資訊 parent.jsximport react,from react import son from components test1 class parent extends component render export default parent c...

React元件通訊

分類 父子元件通訊 無論父元件傳遞是props還是state,子元件都是通過props接收 子父元件通訊 父元件傳遞方法給子元件,子元件呼叫父元件傳遞過來的方法 注意 自己的狀態自己更改 非父子元件通訊 ref鏈 1.ref this.refs.2.ref this.推薦 跨元件通訊 context...

React元件通訊 高階元件

子父元件通訊 非父子元件通訊 跨元件通訊 在react沒有類似vue中的事件匯流排來解決這個問題,我們只能借助它們共同的父級元件來實現,將非父子關係裝換成多維度的父子關係。react提供了contextapi來實現跨元件通訊,react 16.3之後的contextapi較之前的好用。使用流程 im...