生活随笔
收集整理的這篇文章主要介紹了
react --- 隔代传递参数的三种方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
組件跨層級(jí)通信 - Context
- 上下文提供一種不需要每層設(shè)置props就能跨多級(jí)組件傳遞數(shù)據(jù)的方式
方式1
- Provider提供值
- Consumer來(lái)消費(fèi)傳遞的值
import React
from 'react';
const Mycontext
= React
.createContext();
const { Provider
, Consumer
} = MyContext
;function Child(prop
) {return <div
>Child
: {prop
.foo
} </div
>
}export default function ContextTest() {return (<div
><Provider value
={ {foo
: 'bar'} }><Consumer
>{value
=> <Child
{...child
} />}</Consumer
></Provider
></div
>)
}
方式2
- 使用hook來(lái)消費(fèi)(useContext)
import React
, {useContext
} from 'react';
const { Provider
} = MyContext
;const MyContext
= React
.createContext();
function Child2() {const ctx
= useContext(MyContext
);return <div
>Child2
: {ctx
.foo
} </div
>
}export default function ContextTest() {return (<div
><Provider value
={{foo
: 'bar'}}><Child2
></Child2
></Provider
></div
>)
}
方式3
- 使用class指定靜態(tài)contextType
import React
from 'react'
const MyContext
= React
.createContext();class Child3 extends React.Component{static contextType
= MyContext
;render(){return <div
>Child3
: {this.context
.foo
}</div
>}
}export default function ContextTest() {return (<div
><Provider value
={{foo
: 'bar'}}><Child3
></Child3
></Provider
></div
>)
}
總結(jié)
以上是生活随笔為你收集整理的react --- 隔代传递参数的三种方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。