2016-09-20 49 views
1

我的代碼有什麼問題?我在jsbin的控制檯中看到沒有錯誤。React hello world不適用於ES6

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渲染多個組件()?

+1

類名必須以大寫字母開頭。 –

+0

http://imgur.com/a/KuPUr – Quentin

+0

@Whitcik沒有解決問題 – dfox

回答

2

有一些小的語法錯誤讓你失望。小寫的類,大寫的命名組件,並關閉要渲染的組件。下面的代碼在你的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') 
); 
0

如果您想使用道具,您(可能)需要一個構造函數(請參閱下面的評論)。

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.

+0

這是不正確的。你需要使用構造函數來使用'this.state',但道具自動應用。 –

+0

你說得對,@JoshuaComeau,但是如果你想在構造函數中使用道具,那麼你需要使用'super(道具)'。請參閱http://codepen.io/tomekbuszewski/pen/XjNWqq?editors=0010 –

+0

True - 如果您定義了自己的構造函數,則需要確保「Component」的原始構造函數仍然接收道具。否則,你的構造函數會覆蓋原來的構造函數,並且'this.props'永遠不會被設置。 –

2

首先,你必須使用ReactDOM來渲染組件的瀏覽器不React。 你的代碼是:

React.render(
    <secondComponenent id="abc" />, 
    document.getElementById('react_example') 
); 

但在最新版本的React(0.14以上),它必須是:

ReactDOM.render(
    <secondComponenent id="abc" />, 
    document.getElementById('react_example') 
); 

爲了使它工作,你可以將此library添加到您的HTML。

其次,當它沒有像這樣的子組件時,你必須關閉你的組件:<secondComponent id="abc" />,你的文字是這樣的:<secondComponent id="abc">

爲了呈現多個成分發生化學反應,你有這樣的例如單親組件包起來:

ReactDOM.render(
    <div> 
     <firstComponenent id="abc" /> 
     <secondComponenent id="abc" /> 
    </div>, 
    document.getElementById('react_example') 
); 

P.S:此外,如@ alexi2說:class SomeComponentClass SomeComponent

+0

不,reactDOM是不需要的,看看http://jsbin.com/cuneha/1/edit?js,output – dfox

+0

是的,你是對的,如果'react'版本低於'0.14'則不需要。但是最近的版本無論如何都必須使用'ReactDOM'。也許幫助:http://stackoverflow.com/questions/33007402/is-there-any-difference-between-react-render-and-reactdom-render。 – sehrob

+0

謝謝不知道! – dfox