日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React組件通信實現流程詳解_React

作者:花鐺 ? 更新時間: 2022-12-28 編程語言

組件間的關系

  • 父子組件
  • 兄弟組件
  • 祖孫組件

通信方式

  • 通過 props 方式傳遞數據。
  • Context 方式(一般用于祖孫組件通信)。
  • 集中式狀態管理 Redux(一般用于很多組件間都要共享數據的情況下)。

父子組件通信

父子組件通信一般通過 props 方式傳遞數據。

父組件向子組件傳遞數據:

父組件通過向子組件傳遞 props,子組件得到 props 后進行相應的處理。

// Parent.js
import React, { Component } from "react";
import Child from "./Child.js";
export default class Parent extends Component{
    render(){
        return(
            <div>
            	// 父組件通過 props 向子組件傳遞參數
                <Child title = "父組件向子組件通信" />
            </div>
        )
    }
}
// Child.js
import React,{ Component } from "react";
export default class Child extends Component{
    render(){
        return(
        	// 子組件通過 this.props 接收父組件傳遞過來的參數
            <div>{this.props.title}</div>
        )
    }
}

子組件主動觸發父組件方法,向父組件傳遞數據:

父組件將一個函數作為 props 傳遞給子組件,子組件調用該函數,便可以向父組件通信。

// Parent.js
import React,{ Component } from "react";
import Child from "./Child.js";
export default class Parent extends Component{
	handleChange(val){
		console.log(val) // 我是子組件傳給父組件的值
	}
    render(){
        return(
            <div>
            	// 父組件通過 props 把方法傳遞給子組件
                <Child handleChange={this.handleChange} />
            </div>
        )
    }
}
// Child.js
import React,{ Component } from "react";
export default class Child extends Component{
	handleClick(){
		// 子組件接收并調用父組件傳遞過來的方法
		this.props.handleChange(‘我是子組件傳給父組件的值')
	}
    render(){
        return(
           <button onClick={this.handleClick}>按鈕</button>
        )
    }
}

父組件主動觸發子組件方法,獲取子組件數據:

// Parent.js
import React,{ Component } from "react";
import Child from "./Child.js";
export default class Parent extends Component{
	childRef = React.createRef()
	handleClick(val){
	    //父組件觸發子組件方法
		this.childRef.current.handleChange() 	
	}
    render(){
        return(
            <div onClick={this.handleClick}>
            	// 父組件通過 props 把方法傳遞給子組件
                <Child ref={this.childRef} />
            </div>
        )
    }
}
// Child.js
import React,{ Component } from "react";
export default class Child extends Component{
	handleChange(){
		// 子組件執行邏輯操作
		...
		// 子組件返回數據,傳遞給父組件
		// return {}
	}
    render(){
        return(
           <button onClick={this.handleChange}>按鈕</button>
        )
    }
}

原文鏈接:https://blog.csdn.net/wsln_123456/article/details/109157645

欄目分類
最近更新