ReactDOM.render渲染页面

时间:2019-07-11 00:20:20

标签: javascript html reactjs

ReactJS的新手, 找不到为什么该页面没有显示任何内容-

<!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

            <script src="react.16.8.6.development.js"></script>
            <script src="react-dom.16.8.6.development.js"></script>
            <script src="babel.7.5.4.min.js"></script>
        </head>

        <body>
            <div id="container"></div>

            <script type="text/babel">

                class MyClass extends React.Componet{
                    render() {
                        return(<h1>Hello React Componets!</h1>);
                    }
                }

                ReactDOM.render(
                    <h1>MyClass</h1>,
                    document.getElementById('container')
                );
            </script>
        </body>
    </html>

控制台出现错误-

VM43:19未捕获的TypeError:超级表达式必须为null或_inherits(:19:113)处的函数     在:26:3     在:42:2

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

<script type="text/babel">

    class MyClass extends React.Component{
        render() {
            return(<h1>Hello React Componets!</h1>);
        }
    }

    ReactDOM.render(
        <h1><MyClass/></h1>,
        document.getElementById('container')
    );
</script>

答案 1 :(得分:1)

您的问题在这里,

<h1>MyClass</h1>, //This is not a react component, this will only print `MyClass` as text on page

只需更改

ReactDOM.render(
     <h1>MyClass</h1>,
     document.getElementById('container')
);

对此,

ReactDOM.render(
    <MyClass />,
    document.getElementById('container')
);

注意:更正代码中的错字, class MyClass extends React.Componet应该是class MyClass extends React.Component{

Demo