我是使用 React 构建应用程序的新手。直接从repo下载“入门”应用程序后我启动了服务器并且默认应用程序正确呈现。我尝试按照教程 here 添加菜单组件,但是应用程序在编译后没有错误的情况下无法渲染。为了了解更多上下文,此应用程序保存在名为 App.js 的文件中,而不是扩展名为 .jsx 的文件中。
我认为问题在于通过 {} 将 JS 代码插入到 MenuExample.render()
内的 HTML 中。如果我用函数中注释掉的简单 HTML 代码替换 MenuExample.render()
的主体,应用程序就会呈现。有人可以解释一下为什么应用程序不渲染吗?感谢您的所有帮助。
请参阅下面的完整代码。
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>
最佳答案
您尝试在使用 es6
类创建的 React 组件中使用 getInitialState
生命周期方法,但该方法不受支持。您应该更改为构造函数并在其中设置初始状态。
class MenuExample extends Component {
// eslint-disable-next-line
constructor(props) {
super(props);
this.state = { focused: 0 };
}
...
已说明here .
关于javascript - 在 HTML 中使用 JS 时 React 应用程序不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770541/