[英]React App Not Rendering When Using JS in HTML
I'm new to building apps using React. 我是使用React构建应用程序的新手。 After downloading the 'Getting Started' app directly from the repo I started the server and the default app rendered properly.
直接从仓库下载“入门”应用程序后,我启动了服务器并正确呈现了默认应用程序。 I tried to add a Menu component by following the tutorial here , but the app fails to render after compiling with no errors.
我尝试按照此处的教程添加Menu组件,但是该应用在编译后没有出现错误而无法呈现。 For more context, this app is saved in a file called App.js, not a file with .jsx extension.
有关更多上下文,此应用程序保存在名为App.js的文件中,而不是扩展名为.jsx的文件中。
I think the issue is with the insertion of JS code via {} into the HTML within MenuExample.render()
. 我认为问题在于通过{}将JS代码插入
MenuExample.render()
的HTML中。 If I replace the body of MenuExample.render()
with the simple HTML code commented out in the function, the app renders. 如果我用函数中注释掉的简单HTML代码替换
MenuExample.render()
的正文,则该应用程序将呈现。 Can someone please shed some light as to why the app isn't rendering? 有人可以说明为什么该应用无法呈现吗? Thanks for all the help.
感谢您的所有帮助。
Please see the full code below. 请查看下面的完整代码。
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; /* eslint no-var:0*/ /* eslint func-names:0*/ /* eslint prefer-arrow-callback:0*/ /* eslint class-methods-use-this:0*/ class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> <MenuExample items={ ['Home', 'Services', 'About', 'Contact Us'] }/> </div> ); } } class MenuExample extends Component { // eslint-disable-next-line getInitialState() { return { focused: 0 }; } clicked(index) { this.setState({ focused: index }); } // eslint-disable-next-line render() { var self = this; return ( <div> <ul>{this.props.items.map(function (m, index) { var style = ''; if (self.state.focused === index) { style = 'focused'; } return <li className={style} onClick={self.clicked.bind(self, index)}>{m}</li>; }) } </ul> <p> Selected: {this.props.items[this.state.focused]} </p> </div> // Simple HTML that works // <p> Foo </p> ); } } export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
You're trying to use the getInitialState
lifecycle method inside your react component created using es6
classes, which isn't supported. 您正在尝试在不支持使用
es6
类创建的react组件中使用getInitialState
生命周期方法。 You should change to a constructor and setting your initial state inside of it. 您应该更改为构造函数,并在其中设置初始状态。
class MenuExample extends Component {
// eslint-disable-next-line
constructor(props) {
super(props);
this.state = { focused: 0 };
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.