函数作为 React 子项无效。如果您 return 一个组件而不是来自渲染,则可能会发生这种情况

Functions are not valid as a React child. This may happen if you return a Component instead of from render

我写了一个高阶组件:

import React from 'react';


const NewHOC = (PassedComponent) => {
    return class extends React.Component {
        render(){
            return (
                <div>
                    <PassedComponent {...this.props}/>
                </div>
            )
        }
    }
}

export default NewHOC;

我在 App.js 中使用上面的内容:

import React from 'react';
import Movie from './movie/Movie';
import MyHOC from './hoc/MyHOC';
import NewHOC from './hoc/NewHOC';
export default class App extends React.Component {
  render() {
   return (
    <div>
     Hello From React!!
     <NewHOC>
        <Movie name="Blade Runner"></Movie>
     </NewHOC>
    </div>
   );
  }
 }

但是,我收到的警告是:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in NewHOC (created by App) in div (created by App) in App

Movie.js 文件是:

import React from "react";

export default class Movie extends React.Component{
    render() {
        return <div>
            Hello from Movie {this.props.name}
            {this.props.children}</div>
    }
}

我做错了什么?

您将其用作常规组件,但它实际上是一个 returns 组件的函数。

尝试做这样的事情:

const NewComponent = NewHOC(Movie)

你会像这样使用它:

<NewComponent someProp="someValue" />

这是一个 运行 示例:

const NewHOC = (PassedComponent) => {
  return class extends React.Component {
    render() {
      return (
        <div>
          <PassedComponent {...this.props} />
        </div>
      )
    }
  }
}

const Movie = ({name}) => <div>{name}</div>

const NewComponent = NewHOC(Movie);

function App() {
  return (
    <div>
      <NewComponent name="Kill Bill" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>

所以基本上NewHOC只是一个接受组件的函数和returns一个渲染传入组件的新组件。我们通常使用这种模式来增强组件和共享逻辑或数据。

您可以在 docs and I also recommend reading about the difference between react elements and components

中阅读有关 HOCS 的信息

我写了一篇 article 关于 React 中共享逻辑的不同方式和模式。

添加到 sagiv 的答案中,我们应该创建 parent 组件,使其可以包含所有 children 组件,而不是 returning child您尝试 return.

的组件

尝试对 parent 组件进行 intentiate 并在其中传递 props 以便所有 children 都可以像下面那样使用它

const NewComponent = NewHOC(Movie);

这里 NewHOC 是 parent 组件,它的所有 child 都将使用电影作为道具。

但是无论如何,你 guyd6 已经为新的 React 开发人员解决了一个问题,因为这可能也是一个可能会出现的问题,在这里他们可以找到解决方案。

在我的例子中,我从父级传输 class 组件并在内部使用它作为 prop var,使用 typescript 和 Formik,运行 就像这样:

父级 1

import Parent2 from './../components/Parent2/parent2'
import Parent3 from './../components/Parent3/parent3'

export default class Parent1 extends React.Component {
  render(){
    <React.Fragment>
      <Parent2 componentToFormik={Parent3} />
    </React.Fragment>
  }
}

父 2

export default class Parent2 extends React.Component{
  render(){
    const { componentToFormik } = this.props
    return(
    <Formik 
      render={(formikProps) => {
        return(
          <React.fragment>
            {(new componentToFormik(formikProps)).render()}
          </React.fragment>
        )
      }}
    />
    )
  }
}

在我的例子中,我忘记在 react 组件的渲染函数中的函数名称后添加 ()

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

更改渲染方法,如错误消息中所述

        <div className="aaa">
            {this.renderView()}
        </div>

解决了问题

当您直接从 jsx 调用函数而不是在事件中调用函数时,也会发生这种情况。喜欢

这样写会报错

<h1>{this.myFunc}<h2>

写就可以了:

<h1 onClick={this.myFunc}>Hit Me</h1>

我能够通过在导出 class 组件之前调用我的高阶组件来解决这个问题。我的问题是专门使用 react-i18next 及其 withTranslation 方法,但这里是解决方案:

export default withTranslation()(Header);

然后我能够像最初希望的那样调用 class 组件:

<Header someProp={someValue} />

我是这样从 webpack 延迟加载中获取的

import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: Loader, // warning
});
render() {
    return <WishlistPageComponent />;
}


// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: '', // all good
});    

这样做会有什么问题;

<div className="" key={index}>
   {i.title}
</div>

[/*Use IIFE */]

{(function () {
     if (child.children && child.children.length !== 0) {
     let menu = createMenu(child.children);
     console.log("nested menu", menu);
     return menu;
   }
 })()}

我在按照此处的说明操作时遇到了这个错误:https://reactjs.org/docs/add-react-to-a-website.html

这是我得到的:

ReactDOM.render(Header, headerContainer);

应该是:

ReactDOM.render(React.createElement(Header), headerContainer);

就我而言,我忘记删除这部分“() =>”。愚蠢的 ctrl+c+v 错误。

const Account = () => ({ name }) => {

所以应该是这样的:

const Account = ({ name }) => {

我也确实遇到了这个错误,因为我在路由时没有使用正确的 snytax。这是在我的 App.js 下的 部分:

假:

<Route path="/movies/list" exact element={ MoviesList } />

正确:

<Route path="/movies/list" exact element={ <MoviesList/> } />

现在 MoviesList 被识别为一个组件。

我也有这个错误。问题是如何调用函数。

代码错误:

const Component = () => {
    const id = ({match}) => <h2>Test1: {match.params.id}</h2>
    return <h1>{id}</h1>;
};

id 是一个函数,所以:

正确代码:

return <h1>{id()}</h1>;

就我而言

<Link key={uuid()} to="#" className="tag">
  {post.department_name.toString}
</Link>

更改为

<Link key={uuid()} to="#" className="tag">
  {post.department_name.toString()}
</Link>