使用React与typescript但在ES5中正常工作时,this.props.xxx是未定义的?

Dir*_*ind 4 javascript reactjs react-native

最近我开始学习与ES5的反应,但现在尝试在我的应用程序中使用Type脚本.任何人都可以告诉我为什么我无法使用{this.props.people}打印值,但是当我使用{this.state.people}时它正在按预期工作.我从这个网站上做了一些例子.请告诉我这里缺少什么?

现场

import * as React from 'react';

class About extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        console.log(About);
        const people = [];

        for (let i = 0; i < 10; i++) {
            people.push({
                name: i,
                country: i + i
            });
        }

        this.state = {people};
    }
    public render() {
        return (
            <div>
            {this.props.people.map((person: any, index: number) => (
                <p key={index}>Hello, {person.name} from {person.country}!</p>
            ))}
        </div>
        );
    }
}
export default About;
Run Code Online (Sandbox Code Playgroud)

Nan*_*ndi 7

因为this.props.people当您的父组件发送人道具时会填充这些内容.this.state.people是可访问的,因为您在构造函数中设置它.

它与ES5or 无关ES6.顺便提一下,您正在使用ES6箭头功能.

class Parent extends React.Component {
  render(
    return (
      <Child people=[1, 2, 3] />
    )
  )
}

class Child extends React.Component {
  constructor(props) {
    this.state = {
      people: [5, 6, 7]
    }
  }

  render() {
    return ( 
      <div>
        {this.props.people} // Will render [1, 2, 3], coming from Parent
        {this.state.people} // Will render [5, 6, 7], coming from Constructor
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)