React Context 函数组件的主流写法

基础写法

// 定义Context - index.js
import React, { createContext } from 'react';
import colors from './color-data';
import { render } from 'react-dom';
import App from './App';

export const ColorContext = createContext(); // 导出Context

render(
  <ColorContext.Provider value={{ colors }}>
    <App />
  </ColorContext.Provider>,
  document.getElementById("root")
)

// 使用Context
import React, { useContext } from 'react';
import { ColorContext } from './index.js';
import Color from './Color';

export default function ColorList() {
  const { colors } = useContext(ColorContext);

  if (!colors.length) return <div>No Colors Listed. (Add a Color)</div>;

  return (
    <div>
      {
      	colors.map(color => <Color key={color.id} {...color} />)
      }
    </div>
  )
}

进阶写法 - 响应式的Context

// 定义Context
import React, { createContext, useState } from 'react';
import colorData from './color-data.json';

const ColorContext = createContext();

export default function ColorProvider({ children }) {
  const [colors, setColors] = useState(colorData);

  return (
    <ColorContext.Provider value={{ colors, setColors }}>
      {children}
  	</ColorContext.Provider>
  )
}

// 定义Context
import React, { createContext, useState } from 'react';
import colorData from './color-data.json';

const ColorContext = createContext();

export default function ColorProvider({ children }) {
  const [colors, setColors] = useState(colorData);

  const rateColor = (id, rating) => setColors(...);
  const removeColor = id => setColors(...);
  const addColor = (title, color) => setColors(...);

  return (
    <ColorContext.Provider value={{ colors, rateColor, removeColor, addColor }}>
      {children}
  	</ColorContext.Provider>
  )
}

最好不要把setColors传给消费组件,因为变更操作有多种,应该为不同操作定义函数,只开放允许用户执行的修改操作函数


主流写法 - 自定义钩子封装Context

// color-hooks.js
import React, { createContext, useState, useContext } from 'react';
import colorData from './color-data.json';

const ColorContext = createContext();

export const useColors = () => useContext(ColorContext);

import React, { useContext } from 'react';
import { ColorProvider } from './color-hooks.js';
import { render } from 'react-dom';
import App from './App';

render(
  <ColorProvider>
    <App />
  </ColorProvider>,
  document.getElementById("root")
)

// 使用Context
import React, { useContext } from 'react';
import Color from './Color';
import { useColors } from './color-hooks';

export default function ColorList() {
  const { colors } = useColors();

  return (...)
}

内容出自《React学习手册(第二版)- 中国电力出版社》,强烈推荐*****

你可能感兴趣的:(React,react.js)