如何在React Component中定义函数?

时间:2017-01-09 07:06:05

标签: reactjs

我在reactjs中做了我的第一步。这段代码应写入" ON",但我收到错误:

  

App.js:预期的意外令牌(

代码:

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;

我错过了什么?

2 个答案:

答案 0 :(得分:0)

您编写formatLightState函数的方式不正确。您还需要绑定该函数以访问该状态。为了绑定,您可以使用arrow函数或bind it in the constructor

&#13;
&#13;
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'));
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

问题是function关键字。要在反应组件内定义函数,您不需要使用它。

像这样写:

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

Jsfiddlehttps://jsfiddle.net/ynx2evyj/