reactjs代码没有出现在浏览器中

时间:2017-05-23 02:27:14

标签: javascript reactjs

感谢这里的伟大工作。我是react.js的新手,有一些有限的js 技能。我正在尝试创建一个带有标题,主页和页脚的基本页面。我写了代码,控制台没有返回错误,但没有任何东西出现在浏览器中。这是代码:

JS

const Header = ({title}) => (<header>{title}</header>);
const Main = ({title}) => (<main>{title}</main>);
const Footer = ({title}) => (<footer>{title}</footer>);

class App extends React.Component {
    render() {
        const {header,main,footer} = this.props;
        return (
            <div className="app">
                <Header title={header} />
                <Main title={main} />
                <Footer title={footer}/>
            </div>
        );
    }
};

ReactDOM.render(
    <App
        header="I am the header"
        main="I am the main"
        footer="I am the footer" />,
    document.getElementById('react')
);




export default App;

html

<body>


  <div id="react"></div>


  </body>

控制台返回:

Compiled successfully!

You can now view wp in the browser.

  http://localhost:38867/

Note that the development build is not optimized.
To create a production build, use npm run build.

我得到了这个:

enter image description here

我做错了什么? codeview https://codepen.io/anon/pen/mmaxvj

编辑:我忘了添加index.js。我对其进行了编辑,并将ReactDOM.render (<App />, document.getElementById('root'));更改为ReactDOM.render(<App />, document.getElementById('react'));

现在我有一个空白页面,浏览器上没有更多错误......有什么想法吗?

2 个答案:

答案 0 :(得分:0)

尝试在结束</body>代码之前添加此代码:

<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js'></script>

检查您是否还需要jquery.js或任何其他javascript包。

我在React doc页面上看到,它们提供了CodePen“Hello World”React页面的链接 - 您也可以将其用作种子模板:http://codepen.io/gaearon/pen/ZpvBNJ?editors=0010

这来自页面https://facebook.github.io/react/docs/hello-world.html

答案 1 :(得分:0)

您提供的代码有效。但是,您在问题中包含的屏幕截图显示document.getElementById('root')行不属于您的代码 - 您可能需要重新构建代码或确保您的开发服务器(例如webpack)在正确的源代码上运行目录。

另请查看有关反应<script>标记的展示位置的答案:https://stackoverflow.com/a/26416407/1647737

const Header = ({title}) => (<header>{title}</header>);
const Main = ({title}) => (<main>{title}</main>);
const Footer = ({title}) => (<footer>{title}</footer>);

class App extends React.Component {
    render() {
        const {header,main,footer} = this.props;
        return (
            <div className="app">
                <Header title={header} />
                <Main title={main} />
                <Footer title={footer}/>
            </div>
        );
    }
};

ReactDOM.render(
    <App
        header="I am the header"
        main="I am the main"
        footer="I am the footer" />,
    document.getElementById('react')
);
<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="react"></div>