將孫子組件中的值傳給父組件 - React

需求分析


需求: 點擊孫子組件, 將點擊的父組件的index顯示出來, 這時就要將父組件的index傳給子組件,然後在傳給孫子組件,這時通過點擊對應的孫子組件,再將點擊的孫子組件再通過子組件傳給父組件

在這裏插入圖片描述

在這裏插入圖片描述

Father.js


// 父親組件
export default class Father extends Component{
    constructor(props) {
        super(props);
        // 接收子組件傳來的值的固定套路
        this.handleLawClick=this.handleLawClick.bind(this)
        this.state={
            law_click_count: 0
        }
    }
    render() {
        return(
            <div>
                {
                    this.state.basic_list.map((item,index)=>{
                        return(
                            <Son
                            	data={item}
                            	// 傳給兒子組件的index值
                                index={index}
        						// 重點: 接收孫子傳給兒子組件的值, 由於是props, 所以只能通過函數來接收, 這也是固定套路
                                handleLawClick={this.handleLawClick}
                            />
                        )
                    })
                }
            </div>
        )
    }
    // 固定套路
    handleLawClick(val) {
        this.setState({law_click_count: val});
    }
}

Son.js


// 兒子組件
export default class Son extends Component {
    constructor(props) {
        super(props);
        this.state={
            items=this.props.data,
            // 初始化值來接收父組件的index
            law_index:0
        }
        
    }
    render() {
        // 接收父組件傳來的index的值
        this.state.law_index=this.props.index
        return(
            <div>
                {items.map((item, index)=>{
                    return(
                        <Grandson
                        	data={item}
        					index={index}
                        	// 將接收的父組件的值傳給孫子組件
							law_index={this.state.law_index}
        					// 重點: 通過定義handleLawClick_item屬性,來接收孫子組件傳來的值, 並將傳過來的值賦給了父組件的handleLawClick
                            handleLawClick_item={this.props.handleLawClick}
                    )
                  })
                }
            </div>
        )
    }
}

Grandson.js


// 孫子組件
export default class Grandson extends Component {
    constructor(props) {
        super(props);
        this.data=this.props.data
        // 接收兒子組件傳來的值
        this.law_index_item=this.props.law_index
    }
	
	render() {
        return (
            <div>
            	<span onClick={()=>this.click(this.props.index)}>{this.data[0]}</span>
            <div>
        )
    }
    
    click=(i)=>{
        // 注意: 參數i是 兒子組件的index, 這個和父組件的index有很大的區別的!
        // 重點: 孫子組件的值傳給兒子組件
        this.props.handleLawClick_item(this.law_index_item)
    }
}

在這裏插入圖片描述
看上面動圖, 你可以看到通過點擊法條, 最後顯示的數字變化.

可以很直觀的看到:

  • law_click_index的值是遍歷子組件傳過來的(index+1)
  • law_click_count的值則是通過父組件的index傳給子組件在傳給孫子組件,在傳回來.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章