[英]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.