React學習筆記②

import React,{Component} from 'react';

import Child from './Child.js'
class App extends Component{
  constructor(){
    //初始化屬於組件的屬性
    super();
    this.state = {
      age:12,
      name:'234'
    }
  }
  render(){
    //結構賦值
    let {age,name} = this.state;
    return(
     <div>
       {/* 組件的使用必須大寫 */}
       <Child age={age} name={name}>
        <ul>
          <li>1</li>
          <li>2</li>
          <li>3</li>
        </ul>
       </Child>
     </div>
    )
  }
}
export default App;

父組件App.jsreact

age={age} name={name}傳遞給Child.js
 1 //使用jsx必須引入React
 2 import React,{Component} from 'react';
 3 class Child extends Component{
 4   constructor(props){
 5     //初始化屬於組件的屬性
 6     super(props);
 7     
 8   }
 9   render(){
10     console.log(this.props)
11     //聲明一個age,name屬性,this.props中同名屬性進行賦值
12     let {age,name} = this.props;
13 
14 
15   //this.props.children(三種數據格式)
16     return(
17       <div>
18           child:{age}{name}
19           {this.props.children}
20       </div>
21     )
22   }
23 }
24 export default Child;

子組件Child.jsthis

let {age,name} = this.props;接收App.js傳遞的數據
this.props.children;接收App.js傳遞的DOM

以上是父組件向子組件傳遞數據spa

相關文章
相關標籤/搜索