[英]React hello world doesn't work with ES6
我的代码有什么问题? 我在jsbin的控制台中看不到任何错误。
http://jsbin.com/susumidode/edit?js,console,output
Class secondComponenent extends React.Component {
render(){
return (
<p>My id is: {this.props.id}</p>
);
}
}
React.render(
<secondComponenent id="abc">,
document.getElementById('react_example')
);
还有如何在React.render()中渲染多个组件?
有一些较小的语法错误使您退缩。 类的小写字母,命名组件的大写字母,以及关闭要渲染的组件。 下面的代码可在您的JSBin中使用。
class SecondComponent extends React.Component {
render(){
return (
<p>My id is: {this.props.id}</p>
);
}
}
React.render(
<SecondComponent id="abc" />,
document.getElementById('react_example')
);
首先,必须使用ReactDOM
将组件呈现给浏览器而不是React
。 您的代码是:
React.render(
<secondComponenent id="abc" />,
document.getElementById('react_example')
);
但是在最新版本的React
(高于0.14)中,它必须是:
ReactDOM.render(
<secondComponenent id="abc" />,
document.getElementById('react_example')
);
要使其工作,您可以将此库添加到html中。
其次,必须在没有子组件这样的子组件时关闭它: <secondComponent id="abc" />
,这样子的写作是: <secondComponent id="abc">
。
为了在反应中呈现多个组件,您必须使用单个父组件包装它们,例如:
ReactDOM.render(
<div>
<firstComponenent id="abc" />
<secondComponenent id="abc" />
</div>,
document.getElementById('react_example')
);
PS :另外,正如@ alexi2所说: class SomeComponent
不是Class SomeComponent
。
如果您想使用道具,则(可能)需要一个构造函数(请参阅此答案下方的注释)。
import React, { Component } from 'react';
import { render } from 'react-dom';
class SecoundComponent extends Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<p>My id is: {this.props.id}</p>
)
}
}
render(<SecoundComponent id="123" />, document.getElementById('react_example'));
另请注意,我将类SecoundComponent
命名为大写S。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.