2016-09-20 6 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

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')); 

はまた、資本S.

+0

これは当てはまりません。 'this.state'を使うにはコンストラクタを使う必要がありますが、propsは自動的に適用されます。 –

+0

あなたは正しいですが、@ JoshuaComeauですが、コンストラクタ内で小道具を使いたい場合は、 'super(props)'を使う必要があります。 http://codepen.io/tomekbuszewski/pen/XjNWqq?editors=0010 –

+0

Trueを参照してください。独自のコンストラクタを定義する場合、 'Component'の元のコンストラクタが依然としてそのプロップを受け取るようにする必要があります。それ以外の場合、コンストラクタは元のものを上書きし、 'this.props'は決して設定されません。 –

2

まずで、私はクラスSecoundComponentの名前ことに注意してください、あなたはブラウザではないReactにコンポーネントをレンダリングするためにReactDOMを使用する必要があります。

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

しかし(0.14以上)Reactの最近のバージョンではそれがなければなりません: あなたのコードがある

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

それはあなたがあなたのhtmlにこのlibraryを追加することができます動作するように。

次のような子コンポーネントがない場合は、コンポーネントを終了する必要があります。<secondComponent id="abc" /><secondComponent id="abc">のように記述します。

反応で複数のコンポーネントをレンダリングするために、あなたはこのような例のための単一の親コンポーネントでそれらをラップする必要があります。

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

P.S:また、@ alexi2と言う:class SomeComponentないClass 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

関連する問題