2017-01-09 12 views
0

私はreactjsで私の最初のステップをやっています。このコードは、 "ON" を書き込む必要がありますが、私はエラーを取得:React Componentで関数を定義する方法は?

App.js: Unexpected token, expected (

コード:

import React, { Component } from 'react'; 
import logo from './logo.svg'; 
import './App.css'; 

class Light extends React.Component { 

    constructor(props) { 
     super(props); 
     this.state = {light:"On"}; 
    }; 

    function formatLightState() { 
     return <h1>{this.state.light}</h1> ; 
    } 

    render() { 
     return (
     <div> 
      {this.formatLightState()} 
     </div> 
     ); 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    renderLight(){ 
     return <Light /> 
    } 

    render() { 
    return (
     <div> 
      {this.renderLight()} 
     </div> 
    ); 
    } 
} 

export default App; 

私は何をしないのですか?

答えて

0

formatLightState関数の記述方法が正しくありません。また、状態にアクセスするには関数をバインドする必要があります。バインドするためには、あなたが利用することができるのarrow機能やbind it in the constructor

class Light extends React.Component { 
 

 
    constructor(props) { 
 
     super(props); 
 
     this.state = {light:"On"}; 
 
    }; 
 

 
    formatLightState =() => { 
 
     return <h1>{this.state.light}</h1> ; 
 
    } 
 

 
    render() { 
 
     return (
 
     <div> 
 
      {this.formatLightState()} 
 
     </div> 
 
     ); 
 
    } 
 
} 
 

 
class App extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    } 
 

 
    renderLight(){ 
 
     return <Light /> 
 
    } 
 

 
    render() { 
 
    return (
 
     <div> 
 
      {this.renderLight()} 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script> 
 
<div id="app"></div>

0

問題はfunctionキーワードです。反応成分の中で関数を定義するには、それを使う必要はありません。

formatLightState() { 
    return <h1>{this.state.light}</h1> ; 
} 

Jsfiddlehttps://jsfiddle.net/ynx2evyj/

+0

それが働いたおかげで!

はこのようにそれを書きます。私は信じられない私はこれのために多くの時間を無駄にした:( – user3879322

関連する問題