Reactjs 如何在React组件中定义函数?

Reactjs 如何在React组件中定义函数?,reactjs,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

我正在做我在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;
import React,{Component}来自'React';
从“/logo.svg”导入徽标;
导入“/App.css”;
类。组件{
建造师(道具){
超级(道具);
this.state={light:“On”};
};
函数formatLightState(){
返回{this.state.light};
}
render(){
返回(
{this.formatLightState()}
);
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
}
renderLight(){
返回
}
render(){
返回(
{this.renderLight()}
);
}  
}
导出默认应用程序;

我缺少什么?

您编写
formatLightState
函数的方法不正确。您还需要绑定函数以访问状态。为了绑定,您可以使用
箭头
函数或
在构造函数中绑定它

类灯光扩展React.Component{
建造师(道具){
超级(道具);
this.state={light:“On”};
};
formatLightState=()=>{
返回{this.state.light};
}
render(){
返回(
{this.formatLightState()}
);
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
}
renderLight(){
返回
}
render(){
返回(
{this.renderLight()}
);
}  
}
ReactDOM.render(,document.getElementById('app');

问题是
函数
关键字。要在react组件中定义函数,您不需要使用它

这样写:

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

Jsfiddle

谢谢!它成功了。我真不敢相信我为此浪费了这么多时间:(