除了value属性之外的任何属性都可以在Context.Provider内部工作吗

时间:2019-06-16 22:01:26

标签: reactjs react-context

下面的摘录(摘自docs):

<div style='height: 0'>
  <!-- the quantity of <br> elements must create vertical overflow -->
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <!-- this does not work without the space character -->
  &nbsp;
</div>

我没有将import React from 'react' import { render, cleanup } from '@testing-library/react' import 'jest-dom/extend-expect' import { NameContext, NameProvider, NameConsumer } from '../react-context' afterEach(cleanup) /** * Test default values by rendering a context consumer without a * matching provider */ test('NameConsumer shows default value', () => { const { getByText } = render(<NameConsumer />) expect(getByText(/^My Name Is:/)).toHaveTextContent('My Name Is: Unknown') }) /** * To test a component tree that uses a context consumer but not the provider, * wrap the tree with a matching provider */ test('NameConsumer shows value from provider', () => { const tree = ( <NameContext.Provider value="C3P0"> <NameConsumer /> </NameContext.Provider> ) const { getByText } = render(tree) expect(getByText(/^My Name Is:/)).toHaveTextContent('My Name Is: C3P0') }) /** * To test a component that provides a context value, render a matching * consumer as the child */ test('NameProvider composes full name from first, last', () => { const tree = ( <NameProvider first="Boba" last="Fett"> <NameContext.Consumer> {value => <span>Received: {value}</span>} </NameContext.Consumer> </NameProvider> ) const { getByText } = render(tree) expect(getByText(/^Received:/).textContent).toBe('Received: Boba Fett') }) /** * A tree containing both a providers and consumer can be rendered normally */ test('NameProvider/Consumer shows name of character', () => { const tree = ( <NameProvider first="Leia" last="Organa"> <NameConsumer /> </NameProvider> ) const { getByText } = render(tree) expect(getByText(/^My Name Is:/).textContent).toBe('My Name Is: Leia Organa') }) first传递给last的道具。

假设,这三个定义如下:

NameProvider

我们是否允许在NameContext = createContext() NameProvider = NameContext.Provider NameConsumer = NameContext.Consumer 内传递value道具以外的道具。

如果是,请您分享一个例子。我似乎也无法在react文档中找到它。

提前谢谢! :D

1 个答案:

答案 0 :(得分:1)

从这些文档来看还不是很清楚,但是NameContext.ProviderNameProvider之间存在细微差别。 NameContext.Provider是从React.createContext返回的原始提供者,并且仅以value作为道具。

testing-library文档中,他们没有解释,但是他们创建了一个单独的NameProvider,该文件包装了NameContext.Provider,并提供了一个first/last prop接口,像这样的东西:

const NameProvider = ({ first, last, children }) => (
  <NameContext.Provider value={{ first, last }}>
    {children}
  </NameContext.Provider>
)

这允许您创建具有受限接口的Provider,这在(例如)您正在编写供其他开发人员使用的库并且不想让他们完全访问Provider的库时很有用。 value道具。