2017-12-02 220 views
3

最近我开始学习ES5的反应,但现在试图在我的应用程序中使用类型 脚本。任何人都可以告诉我为什么我无法使用{this.props.people}打印 值,但它在按预期工作,当我 使用{this.state.people}。我已经从这个网站的例子。 请问我这里缺少什么?this.props.xxx是未定义的,但使用与打字稿的反应,但在ES5中正常工作?

Site

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;

回答

7

因为this.props.people的东西,当你父组件派人支撑所填充。因为您正在将它设置在您的构造函数中,因此可以访问this.state.people

它与ES5ES6无关。顺便说一句,你正在使用箭头功能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> 
    ) 
    } 
} 
+0

@Nandu ...是的,你绝对正确,这个例子很清楚......但我有点困惑......假设我的“关于”类是我的例子中的Parent,我想将数据传递给孩子..然后我会像这样发送对吗? –

+0

在'About'的渲染方法中,你需要调用'',是的。然后在'People'组件中,您可以将人员作为'this.props.people'访问。 –

1

这是因为在你的榜样的人的道具是从来没有传下来的,它只是在构造函数中产生和设定的状态,你将不得不使用this.state.people。

如果你想使用道具,你必须通过父组件传递给人。看看components-props documentation

相关问题