React元件傳參

2021-10-05 03:32:32 字數 2261 閱讀 4765

1.基礎傳參

//父元件

//1.傳遞資料

>

//2.傳遞方法

setage =v=

>this.sestate(

setage

>

//子元件

獲取資料

//2.

2.context上下文傳遞引數

特點:引入的context資料是實時更新的,當乙個資料發生改變,所有引用的檢視都會自動更新。

//父元件

//1.匯入型別檢測

import proptypes from 'prop-types'

;//2.定義匯出資料型別

static childcontexttypes =

//3.獲取需要傳遞的資料

getchildcontext())

}}

//子孫元件

//1.定義上下文資料型別

static contexttypes =

//2.使用上下文資料

}>son元件

使用上下文方法

>綠色

3.provider comsumer上下文方式傳遞

//1.定義上下文元件

import react from 'react'

;let

= react.createcontext();

//建立乙個上下文,結構 consumer:消費者, provider:**商

export

//匯出

//父元件

//1.匯入provider

import

from './context'

//2.用provider包裹子元素並傳遞資料

}>

context provider consumer 上下問,提供者,消費者

//子元件

//1.匯入consumer

import

from './context'

//2.通過consumer中的context獲取資料

>

)}

4.redux react-redux(全域性狀態資料共享)

1.安裝

npm i redux react-redux
2.匯入

import

from 'react-redux

3.替換根元件

4.在provider中新增資料倉儲

>
5.編寫store

//資料倉儲

import

from 'redux'

//匯入建立倉庫的方法從 redux裡面

//編寫動作和方法

//處理動作的方法

const initialstate =]}

//初始化資料 count預設值為0,麵包屑導航預設為首頁

const reducer =

(state=initialstate,action)

=>

//當遇到動作是norease 返回乙個新的物件,把原來的state結構,

//加上count屬性,值為以前的count值+1

default: return state;}}

//處理資料的動作

export const actions =)}

//匯出倉庫處理方法

export const store = createstore(reducer)

;

6.元件中使用

1.匯入連線

2.匯出元件

export default connect(mapstatetoprops,mapdispatchtoprops)

mapstatetoprops組state資料對映位元件的props

mapdispatchtoprops 把state中的方法對映為props中的方法

react元件傳參

父元件向子元件傳參 父傳子通過 props 屬性向子元件的attr中傳值 父元件 parent.js import react,from react import child from child export default class parent extends component rende...

react 元件傳參

父元件 render111 return 有狀態元件接受引數 render 我內部的資料 無狀態元件接受引數 import react from react function nostatecomponent props cjs esm export default nostatecomponent...

react父子元件傳參

父子元件通訊主要用到props,如下 在父元件中 import react from react import childcom from childcom.js class parentcom extends react.component export default parentcom 複製 ...