React
中 Context
的使用
context
Context
提供了一种方式,能够让数据在组件树中传递时不必一级一级的手动传递
一般情况下,数据在组件中,要一级一级的传递,单向数据流,比如Parent组件中的theme值,需要在Item组件中使用,就需要我们从Parent中向下传递,
但当我们有了Context
后,我们就不需要一级一级传递了
Parent(theme=red)
List(theme=red)
Item(theme=red)
ThemeContext.Provider value={'red'}
List
ThemeContext.Customer (theme) => { theme }
具体如何使用呢,看下面例子
import React, {
createContext } from 'react';
// 创建Context的唯一方法
const ThemeContext = createContext()
class App extends React.Component {
render () {
return (
// 使用 Context.Provider 包裹后续组件,value 指定值
<ThemeContext.Provider value={
'red'}>
<Middle></Middle>
</ThemeContext.Provider>
)
}
}
class Bottom extends React.Component {
render () {
return (
// Context.Consumer Consumer消费者使用Context得值
// 但子组件不能是其他组件,必须渲染一个函数,函数的参数就是Context得值
<ThemeContext.Consumer>
{
theme => <h1>ThemeContext 的 值为 {
theme}</h1>
}
</ThemeContext.Consumer>
)
}
}
class Middle extends React.Component {
render () {
return <Bottom></Bottom>
}
}
export default App;
当 Provider 提供的值更改时,Consumer 必须重新渲染
import React, {
createContext } from 'react'