網站首頁 編程語言 正文
組件的props:
1.組件是封閉的,要接收外部數據應該通過props來實現。
2.props的作用,接收傳遞給組件的數據。
3.傳遞數據:給組件標簽添加屬性
4.接收數據:函數組件通過參數props接收數據,類組件通過this.props接收數據。
特點:
1.可以給組件傳遞任意類型的數據。
2.props是只讀對象,只能讀取屬性的值,不能修改對象。
3.使用類組件時,如果寫了構造函數,應該將props傳遞給super(),否則無法在構造函數中獲取props。
父->子傳值
import React, { Component } from 'react'
import ComSmall from './ComSmall'
export default class ComBig extends Component {
constructor(){
super()
this.state={
info:"天冷了要加衣"
}
}
render() {
return (
<div>我是父組件
{/* 注冊子組件 ,通過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,傳遞后打印的是數據
}
render() {
return (
<div>我是子組件
{/* 接收父組件傳值 */}
{this.props.msg}
</div>
)
}
}
子->父傳值
利用回調函數,父組件提供回調,子組件調用,將要傳遞的數據作為回調函數的參數。
import React, { Component } from 'react'
export default class ComSmall extends Component {
constructor(){
super()
this.state={
msg:"給你買了一部手機"
}
}
sendMsg(){
// 子組件調用父組件傳遞過來的回調函數
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>
{/* 將回調函數傳遞給子組件 */}
<ComSmall getMsg={this.getChindMsg}></ComSmall>
</div>
)
}
}
原文鏈接:https://blog.csdn.net/qq_72760247/article/details/127885352
相關推薦
- 2022-04-16 ASP.NET?Core命令行界面CLI用法_基礎應用
- 2022-12-08 詳解C++引用變量時那些你不知道的東西_C 語言
- 2022-08-07 C#中struct與class的區別詳解_C#教程
- 2022-04-11 Tomcat訪問不到web應用報錯ORA-01882: 未找到時區的解決方案
- 2022-06-25 python數據可視化之日期折線圖畫法_python
- 2022-05-03 在Django中動態地過濾查詢集的實現_python
- 2022-01-16 ES6箭頭函數、rest參數、擴展運算符、Symbol的使用
- 2022-04-10 微信小程序 base64 圖片 canvas 畫布 drawImage 實現
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支