簡體   English   中英

React 16.3中的上下文組件無效

[英]Context Components in React 16.3 are invalid

我正在嘗試在React 16.3.1中使用新的Context組件。 我正在運行一個非常簡單的例子:

const TestContext = React.createContext();

export default class Test extends Component {
  render () {
    return (
      <TestContext.Provider value="abc">
        <TestContext.Consumer>
          {value => (
            <div>{value}</div>
          )}
        </TestContext.Consumer>
      </TestContext.Provider>
    );
  }
}

但是代碼不會呈現,而是產生此錯誤:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

似乎Provider和Consumer組件都不是有效組件,並且不能由React呈現。

我在這里錯過了什么嗎?

弄清楚了!

我將React更新為16.3.1,但沒有更新ReactDOM。

運行npm uninstall -s react-dom && npm i -s react-dom將其更新為16.3.1並解決了問題。

旁注,我不希望新的Context API依賴於ReactDOM。

對於您當前的情況,您必須在TestContext.Consumer返回一個react元素。

Provider組件在樹中使用得更高,並接受名為value的prop (可以是任何東西)。

Consumer組件在樹中的提供者下面的任何地方使用,並接受名為“children”的prop,它必須是接受該值的函數,並且必須返回react元素(JSX)。

確保你渲染<Test />而不是<TestContext /> ,你必須做出反應並做出反應16.3.1。

const TestContext = React.createContext();

class Test extends React.Component {
  render() {
    return (
      <TestContext.Provider value="abc">
        <TestContext.Consumer>{value => <div>{value}</div>}</TestContext.Consumer>
      </TestContext.Provider>
    );
  }
}

render(<Test />, document.getElementById("root"));

如何使用this.props.children執行此操作的this.props.children

import React from "react";
import { render } from "react-dom";

const TestContext = React.createContext();

class TContext extends React.Component {
  state = {
    value: "abc"
  };
  render() {
    return (
      <TestContext.Provider
        value={{
          state: this.state
        }}
      >
        {this.props.children}
      </TestContext.Provider>
    );
  }
}

class Child extends React.Component {
  render() {
    return (
      <TContext>
        <TestContext.Consumer>
          {context => <div>{context.state.value}</div>}
        </TestContext.Consumer>
      </TContext>
    );
  }
}

render(<Child />, document.getElementById("root"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM