React組件間通訊傳值實(shí)現(xiàn)詳解
組件的props:
1.組件是封閉的,要接收外部數(shù)據(jù)應(yīng)該通過props來實(shí)現(xiàn)。
2.props的作用,接收傳遞給組件的數(shù)據(jù)。
3.傳遞數(shù)據(jù):給組件標(biāo)簽添加屬性
4.接收數(shù)據(jù):函數(shù)組件通過參數(shù)props接收數(shù)據(jù),類組件通過this.props接收數(shù)據(jù)。
特點(diǎn):
1.可以給組件傳遞任意類型的數(shù)據(jù)。
2.props是只讀對(duì)象,只能讀取屬性的值,不能修改對(duì)象。
3.使用類組件時(shí),如果寫了構(gòu)造函數(shù),應(yīng)該將props傳遞給super(),否則無法在構(gòu)造函數(shù)中獲取props。
父->子傳值
import React, { Component } from 'react'
import ComSmall from './ComSmall'
export default class ComBig extends Component {
constructor(){
super()
this.state={
info:"天冷了要加衣"
}
}
render() {
return (
<div>我是父組件
{/* 注冊(cè)子組件 ,通過msg傳遞給子組件*/}
<ComSmall msg={this.state.info}></ComSmall>
</div>
)
}
}import React, { Component } from 'react'
export default class ComSmall extends Component {
constructor(props){
// 此處不傳props
super(props)
this.state={ }
// console.log(this.props);此處打印的是undefined,傳遞后打印的是數(shù)據(jù)
}
render() {
return (
<div>我是子組件
{/* 接收父組件傳值 */}
{this.props.msg}
</div>
)
}
}子->父傳值
利用回調(diào)函數(shù),父組件提供回調(diào),子組件調(diào)用,將要傳遞的數(shù)據(jù)作為回調(diào)函數(shù)的參數(shù)。
import React, { Component } from 'react'
export default class ComSmall extends Component {
constructor(){
super()
this.state={
msg:"給你買了一部手機(jī)"
}
}
sendMsg(){
// 子組件調(diào)用父組件傳遞過來的回調(diào)函數(shù)
this.props.getMsg(this.state.msg)
}
render() {
return (
<div>我是子組件
<button onClick={()=>this.sendMsg()}>給父組件傳值</button>
</div>
)
}
}import React, { Component } from 'react'
import ComSmall from './ComSmall'
export default class ComBig extends Component {
constructor(){
super()
this.state={
data:""
}
}
getChindMsg=(val)=>{
// console.log("獲得子組件傳過來的值:",val);
this.setState({
data:val
})
}
render() {
return (
<div>我是父組件
<p>獲得子組件傳過來的值:{this.state.data}</p>
{/* 將回調(diào)函數(shù)傳遞給子組件 */}
<ComSmall getMsg={this.getChindMsg}></ComSmall>
</div>
)
}
}到此這篇關(guān)于React組件間通訊傳值實(shí)現(xiàn)詳解的文章就介紹到這了,更多相關(guān)React組件通訊傳值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解React setState數(shù)據(jù)更新機(jī)制
這篇文章主要介紹了React setState數(shù)據(jù)更新機(jī)制的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用React框架,感興趣的朋友可以了解下2021-04-04
React為什么需要Scheduler調(diào)度器原理詳解
這篇文章主要為大家介紹了React為什么需要Scheduler調(diào)度器原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
React路由動(dòng)畫切換實(shí)現(xiàn)過程詳解
這篇文章主要介紹了react-router 路由切換動(dòng)畫的實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2022-12-12
React?Router掌握路由搭建與權(quán)限管控的操作方法(?從入門到精通)
本文詳細(xì)介紹了React?Router庫在React應(yīng)用開發(fā)中的應(yīng)用,包括其核心功能、安裝使用、基礎(chǔ)使用、核心組件和功能、路由參數(shù)和嵌套路由、編程式導(dǎo)航以及路由權(quán)限管理等方面,感興趣的朋友一起看看吧2025-01-01
React native ListView 增加頂部下拉刷新和底下點(diǎn)擊刷新示例
這篇文章主要介紹了React native ListView 增加頂部下拉刷新和底下點(diǎn)擊刷新示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04

