2017-12-02 219 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

相關問題