元件跨層級通信 - Context
- 上下文提供一種不需要每層設定props就能跨多級元件傳遞資料的方式
方式1
- Provider提供值
- Consumer來消費傳遞的值
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的孩子展開
{value => <Child {...child} />}
</Consumer>
</Provider>
</div>
)
}
方式2
import React, {useContext} from 'react';
const { Provider } = MyContext;
const MyContext = React.createContext();
// 使用hook消費
function Child2() {
// 使用useContext來擷取傳遞過來的參數,放在ctx裡面
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
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>
)
}