reactjs代码没有出现在浏览器中
Posted
技术标签:
【中文标题】reactjs代码没有出现在浏览器中【英文标题】:reactjs code not showing up in browser 【发布时间】:2017-10-22 19:35:59 【问题描述】:感谢您在这里所做的出色工作。我是 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;
<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.
我得到了这个:
我做错了什么?在这里查看代码https://codepen.io/anon/pen/mmaxvj
编辑:我忘了添加 index.js。我对其进行了编辑并将 ReactDOM.render(<App />, document.getElementById('root'));
更改为 ReactDOM.render(<App />, document.getElementById('react'));
现在我显示了一个空白页面,并且浏览器上没有更多错误...有什么想法吗?
【问题讨论】:
看起来您正在尝试访问尚未创建的名为 root 的元素。 您是否在代码中包含了所有正确的库,例如react.js
?我可能只是错过了它,或者您可能没有发布该部分,但这是使用 React 需要完成的事情。
@Icewine 我没有看到 root ...你在哪里看到它?
在<script>
语句中会有这样的URL:https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js
@KenH。也许你是对的我对反应很陌生。我在哪里可以确保我的所有设置都正确?
【参考方案1】:
尝试在结束 </body>
标记之前添加此代码:
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js'></script>
检查您是否还需要 jquery.js 或任何其他 javascript 包。
我在 React 文档页面上看到,他们提供了 CodePen “Hello World” React 页面的链接 - 您也可以将其用作种子模板:http://codepen.io/gaearon/pen/ZpvBNJ?editors=0010
这来自页面https://facebook.github.io/react/docs/hello-world.html
【讨论】:
【参考方案2】:您提供的代码有效。但是,您在问题中包含的屏幕截图显示了 document.getElementById('root')
行,这不是您的代码的一部分 - 您可能需要重新构建代码或确保您的开发服务器(例如 webpack)在正确的源目录上运行。
还检查这个关于反应<script>
标签位置的答案:https://***.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>
【讨论】:
是的,这是来自 index.js 我在上面添加了代码以上是关于reactjs代码没有出现在浏览器中的主要内容,如果未能解决你的问题,请参考以下文章
Django + ReactJS。 Httponly cookie 没有保存在 React 端的浏览器中。我还在两边都给了 withcredentials : true