React 中 Context的使用

85 阅读1分钟

React中数据是一层一层,从上往下传递的,一般我们会用props进行传递;但是当后代组件需要用到高层组件的数据或者方法,如果用props,会在中间组件也需要进行传递,很麻烦,这时候可以用Context上下文来进行数据的传递

  • 父组件: 创建并暴露context
...
export const Context = React.createContext();
...
//用Context。Provider包裹需要传递数据的后代组件
<Context.Provider value={{ a:1 }}>
      <div>
        <Title />
        <Content chains={chains} status={status} />
      </div>
</Context.Provider>

  • 子组件
  1. 方法一:利用useContext
//引入父组件中暴露的context
import { Context } from '../../父组件';
const reasonContext = () => useContext(Context);
...
return(
    <div>{reasonContext().a}</div>
)
  1. 方法二:利用Context.Consumer
//引入父组件中暴露的context
import { Context } from '../../父组件';
...
return(
    <Context.Consumer>
        <div>{value.a}</div>
    </Context.Consumer>
)