【问题标题】:Functions are not valid as a React child. This may happen if you return a Component instead of <Component> from render函数作为 React 子级无效。如果您从渲染返回 Component 而不是 <Component> ,则可能会发生这种情况
【发布时间】:2021-01-24 04:56:03
【问题描述】:
<script type="text/babel">
    const rootElement = document.getElementById("root");

    const Element = (firstName, lastName) => {
        <div>
            Hello, {firstName} {lastName}
        </div>;
    };

    <Element firstName="John" lastName="Doe" />;

    ReactDOM.render(Element, rootElement);
</script>

函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您在 "firstName, lastName" 中缺少 {} 并返回 div

    <script type="text/babel">
        const rootElement = document.getElementById("root");
    
        const Element = ({firstName, lastName}) => (
            <div>
                Hello, {firstName} {lastName}
            </div>;
        );
    
        ReactDOM.render(<Element firstName="John" lastName="Doe" />, rootElement);
    </script>

    【讨论】:

      【解决方案2】:

      首先 - 如果在 Element 组件中使用花括号 {}arrow function,则需要使用 return 关键字。或者,使用第一个括号 () 而不是花括号。

      第二——你不需要写这行&lt;Element firstName="John" lastName="Doe" /&gt;,而是把这行写在ReactDOM.render里面。或者,将其存储在一个变量中并将其传递到 ReactDOM.render

      <script type="text/babel">
          const rootElement = document.getElementById("root");
      
          const Element = (firstName, lastName) => (
              <div>
                  Hello, {firstName} {lastName}
              </div>;
          );
      
          ReactDOM.render(<Element firstName="John" lastName="Doe" />, rootElement);
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-26
        • 2020-02-20
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多