生活随笔
收集整理的這篇文章主要介紹了
react --- 隔代传递参数的三种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
組件跨層級通信 - 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
=> <Child
{...child
} />}</Consumer
></Provider
></div
>)
}
方式2
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
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
>)
}
總結
以上是生活随笔為你收集整理的react --- 隔代传递参数的三种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。