接下來要做的效果是,在父組件添加兩個按鈕,點擊后改變父組件傳過去的值
父組件
1 import React, { Component } from 'react'; 2 import Test from './component/test'; 3 //聲明welcome組件 4 class welcome extends Component { 5 //聲明一個構造函數 6 constructor(props) { 7 super(props); 8 //this.state是定義組件狀態,可理解為組件中的數據,好比Vue中的data 9 this.state = { 10 userName: '路飛', 11 userAge: 19 12 } 13 } 14 changUserName(){ 15 //要修改this.state中的值,這是唯一的方法 16 this.setState({ 17 userName: '路飛:海賊王的男人' 18 }) 19 } 20 // react元素 一律寫在render函數中 21 render() { 22 return ( 23 <div> 24 {/* 在子組件中聲明一個userName屬性,將this.state.userName的值傳遞到子組件中 */} 25 <Test userName={this.state.userName} userAge={this.state.userAge}></Test> 26 {/* 聲明一個點擊事件后面跟着一個bind(this) 是為了解決this指向問題 ,改變this指向 */} 27 <button onClick={this.changUserName.bind(this)}>改變userName</button> 28 </div> 29 ); 30 } 31 } 32 //最后一定要記住 向外輸出 33 export default welcome;
子組件
1 import React, { Component } from 'react'; 2 3 class test extends Component { 4 render() { 5 return ( 6 <div> 7 <h1>海賊王</h1> 8 {/* 在子組件中用this.props接收父組件中傳遞過來的值 */} 9 {[this.props.userName, this.props.userAge]} 10 11 {console.log(this.props)} 12 {/* 通過控制台打印,this.props是傳遞過來的是一個對象:{userName: "路飛", userAge: 19} */} 13 </div> 14 ); 15 } 16 } 17 18 export default test;