2017-01-09 115 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