默认值的 React.createContext 点? [英] React.createContext point of defaultValue?

查看:29
本文介绍了默认值的 React.createContext 点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React 16 Context 文档页面上,他们提供了与此类似的示例:

On the React 16 Context doc page, they have examples that look similar to this:

const defaultValue = 'light';
const SomeContext = React.createContext(defaultValue);

const startingValue = 'light';
const App = () => (
  <SomeContext.Provider theme={startingValue}>
    Content
  </SomeContext.Provider>
)

似乎 defaultValue 没有用,因为如果您将 startingValue 设置为其他任何内容或不设置它(即 undefined),它会覆盖它.没关系,它应该这样做.

It seems that the defaultValue is useless because if you instead set the startingValue to anything else or don't set it (which is undefined), it overrides it. That's fine, it should do that.

那么 defaultValue 的意义何在?

如果我想要一个不会改变的静态上下文,那么能够只执行以下操作并且让提供程序通过 defaultValue

If I want to have a static context that doesn't change, it would be nice to be able to just do the below, and just have the Provider pass through the defaultValue

const App = () => (
  <SomeContext.Provider>
    Content
  </SomeContext.Provider>
)

推荐答案

当没有 Provider 时,函数 createContext 使用 defaultValue 参数.这有助于在不包装组件的情况下单独测试组件,或使用来自 Provider 的不同值对其进行测试.

When there's no Provider, the defaultValue argument is used for function createContext. This is helpful for testing components in isolation without wrapping them, or testing it with different values from Provider.

代码示例:

import { createContext, useContext } from "react";

const Context = createContext( "Default Value" );

function Child() {
  const context = useContext(Context);
  return <h2>Child1: {context}</h2>;
}

function Child2() {
  const context = useContext(Context);
  return <h2>Child2: {context}</h2>;
}

function App() {

  return (
    <>
      <Context.Provider value={ "Initial Value" }>
        <Child /> {/* Child inside Provider will get "Initial Value" */}
      </Context.Provider>
        <Child2 /> {/* Child outside Provider will get "Default Value" */}
    </>
  );
}

Codesandbox 演示

这篇关于默认值的 React.createContext 点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆