react之context的使用

85 阅读1分钟

context的作用

context是react提供的通过组件数传递数据的方法,用来解决react组件数据传递需要一层一层传递props的问题。

如何使用?

接下来我们将通过一个例子了解context的使用,开发场景中有时会碰到切换主题的需求,我们来看看如何使用context实现一个主题切换的功能。

先来实现一个父组件和需嵌套的子组件

import React from 'react';
const Context = () => {
  return (
      <div>
        <div>father</div>
        <button>切换主题</button>
        <Son></Son>
      </div>
  );
}
const Son = () => {
  return (
    <div style={{ width: '100%', height: '100px' }}>son box</div>

  )
}
export default Context;

编写主题css

index.module.scss

.themeLight {
  background: #fff;
  color: #000;
}
.themeDark {
  background: #000;
  color: #999;
}

使用context

  1. 通过createContext创建一个上下文
  2. 用上下文的provider包裹组件,在value属性中传递所需的值
  3. 在子组件中使用useContext获取context
import React, { createContext, useContext, useState } from 'react';
import Styles from './index.module.scss'  //引入样式文件

const themeContext = createContext(null) //创建上下文
const Context = () => {
  const [theme, setTheme] = useState(Styles.themeLight)
  return (
    //包裹组件并传递值
    <themeContext.Provider value={theme}>
      <div>
        <div>father</div>
        <button onClick={() => setTheme(theme === Styles.themeLight ? Styles.themeDark : Styles.themeLight)}>切换主题</button>
        <Son></Son>
      </div>
    </themeContext.Provider>

  );
}
const Son = () => {
  //获取context
  const theme = useContext(themeContext)
  return (
    <div className={theme} style={{ width: '100%', height: '100px' }}>son box</div>

  )
}
export default Context;