React-props父層屬性傳到子層

1.利用props父層屬性傳到子層

  1. 父層
    List.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    import React, { Component } from 'react';       //載入react核心
    import Item from './Item' //載入Item.js

    class List extends Component{ //創建一個List組件
    render() {
    return(
    <ul>
    //text和num是要傳到子層的屬性,
    //屬性內的文字如果是用{}包起來則是代表數字
    //<Item>文字</Item> 文字也可以傳到子層

    //使用Item組件
    <Item text="學習vue" num="100">筆記vue</Item>
    <Item text="學習react" num={100}>筆記react</Item>
    <Item text="學習angular">筆記angular</Item>
    </ul>
    )
    }
    }

    export default List;
  2. 子層
    Item.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import React, {Component} from 'react';     //載入react核心

    class Item extends Component{ //創建一個Item組件
    render() {
    return(
    <li>
    //接收父層傳來的屬性(text, num)
    {this.props.text} {this.props.num + 1}
    //也可以接收父層傳來的文字
    <p>{this.props.children}</p>
    </li>
    )
    }
    }

    export default Item;
  3. 網頁呈現畫面

    (1)text和num是傳到子層的屬性,
    屬性內的文字如果是用{}包起來則是代表數字,
    (2)文字 文字也可以傳到子層
    段落P的內容this.props.children

分享到