这是react.js教程中的代码," this“关键字表示App类。所以我的问题是为什么我不能只写类名呢?
import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
 persons: [
  { name: 'Max', age: 28 },
  { name: 'Manu', age: 29 },
  { name: 'Stephanie', age: 26 }
 ]
}
render() {
 return (
  <div className="App">
    <h1>Hi, I'm a React App</h1>
    <p>This is reallyyyyyyyy working!</p>
    <button> switch name</button>
    <Person name={App.state.persons[0].name} age={this.state.persons[0].age} />
    <Person name={this.state.persons[1].name} age={this.state.persons[1].age}>My Hobbies: Racing</Person>
    <Person name={this.state.persons[2].name} age={this.state.persons[2].age} />
  </div>
 );
// return React.createElement('div', {className: 'App'}, 
React.createElement('h1', null, 'Hi, I\'m a React App!!!'));
}
}
export default App;发布于 2018-05-28 05:09:07
因为
此关键字引用类的当前实例。它可以用于从构造函数、实例方法和实例访问器中访问成员。
任何面向对象的编程语言都遵循这一规则。但是,如果强制类使用名称作为实例,那么它必须是静态的(不是类本身,而是属性和方法)。
为了您的目的,我们可以将App类创建为模块
class App {
  hello() { return 'Hello World'; }
}
export let AppInstance = new App ();使用
import { AppInstance } from './App';
AppInstance.hello();https://stackoverflow.com/questions/50558575
复制相似问题