React抱怨功能组件无效

时间:2020-08-27 18:02:40

标签: reactjs

我的迷你React应用有问题。

错误显示:“无效的挂钩调用。只能在函数组件的主体内部调用挂钩。”

该函数接受参数并返回React元素,因此根据文档,它应为有效组件。 React和ReactDOM是相同的版本。如果用钩子注释掉该行,则错误消失,组件将呈现。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Small Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script
            src="https://unpkg.com/react@16/umd/react.development.js"
            crossorigin
        ></script>
        <script
            src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
            crossorigin
        ></script>
        <script>
            function MyComponent(props) {
                const [state, setState] = React.useState("");
                return React.createElement("span", null, "Hello Component!");
            }

            const container = document.getElementById("container");
            ReactDOM.render(MyComponent(), container);
        </script>
    </body>
</html>

如何解决?

2 个答案:

答案 0 :(得分:1)

ReactDOM.render(MyComponent(), container);

您将MyComponent作为函数调用,而不是从中创建元素。您需要将其更改为:

ReactDom.render(React.createElement(MyComponent), container);

与JSX等效的是:

ReactDom.render(<MyComponent />, container);

答案 1 :(得分:0)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Small Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script
            src="https://unpkg.com/react@16/umd/react.development.js"
            crossorigin
        ></script>
        <script
            src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
            crossorigin
        ></script>
        <script>
            function MyComponent(props) {
                const [state, setState] = React.useState("");
                return React.createElement("span", null, "Hello Component!");
            }

            const container = document.getElementById("container");
            ReactDOM.render(React.createElement(MyComponent), container);
        </script>
    </body>
</html>