React数据通信父传子和子传父的使用
组件中的props
在react中,props的特点是:
1.可以给组件传递任意类型的数据
2.props是只读的对象,只能够读取属性的值,无法修改对象
如过我们强行修改数据,会报错,告诉我们该属性是只读属性。
ps:在类组件中,如果写了构造函数,应该将props传递给super().
否则无法在构造函数中获取到props
函数组件-父传子
子组件.js
const FunCom = (props) => {
return (
<div>
<h2>我是函数组件</h2>
<p>我叫{ props.name}</p>
</div>
)
}
export default FunCom
页面使用
import React from 'react';
import ReactDOM from 'react-dom';
<!-- 引入 -->
import FunCom from './components/FunCom'
ReactDOM.render(<FunCom name="李大为"/>, document.getElementById('root'))
类组件-父传子
子组件
import React from "react";
class FunCom extends React.Component{
render() {
return (
<div>
<h2>我是函数组件</h2>
<p>我叫{ this.props.name}</p>
</div>
)
}
}
export default FunCom
页面使用
import React from 'react';
import ReactDOM from 'react-dom';
<!-- 引入 -->
import FunCom from './components/FunCom'
ReactDOM.render(<FunCom name="李大为"/>, document.getElementById('root'))
函数组件与类组件接收参数的区别
函数组件接受参数直接是:props.xxx
类组件接受参数直接是: this.props.xxx
组件可以传递那些值?
可以传递:可以传递数字, xxx={19}
html,函数等等....
详细代码如下
父组件
import React from 'react'; //这个是react这个包,我们是需要的
import ReactDOM from 'react-dom'; //这个是react的虚拟dom
import FunCom from './components/FunCom'
ReactDOM.render(<FunCom name="李大为" age={19} fn={() => { console.log('我被出发了')}} tag={<h2>我是H2</h2>} />,
document.getElementById('root'))
子组件
import React from "react";
class FunCom extends React.Component{
render() {
console.log(this.props)
return (
<div>
<h2>我是函数组件</h2>
<p>我叫{this.props.name}</p>
{ this.props.tag}
</div>
)
}
}
export default FunCom
子组件传递数据父组件
1.父组件提供一个回调函数(用于接受数据)
2.将该函数作为属性的值,传递给子组件
儿子组件
import React from "react";
class FunCom extends React.Component{
state = {
msg:'儿子给父亲的数据'
}
// 将数据传递给父组件
giveFtaher = () => {
this.props.giveChildren(this.state.msg)
}
render() {
return (
<div>
<p>我是函数组件</p>
<button onClick={this.giveFtaher}>给父组件</button>
</div>
)
}
}
export default FunCom
父组件
import React from 'react'; //这个是react这个包,我们是需要的
import ReactDOM from 'react-dom'; //这个是react的虚拟dom
import FunCom from './components/FunCom'
class PartentHello extends React.Component {
// 当点击按钮的收,子组件会触发这个方法
getMsg = (data) => {
console.log('接收到子组件的数据',data)
}
render() {
return (
<div>
<p>我是主页面</p>
<FunCom giveChildren={ this.getMsg}></FunCom>
</div>
)
}
}
ReactDOM.render(<PartentHello></PartentHello>,document.getElementById('root'))
遇见问题,这是你成长的机会,如果你能够解决,这就是收获。
作者:晚来南风晚相识
出处:https://www.cnblogs.com/IwishIcould/
本文版权归作者所有,欢迎转载,未经作者同意须保留此段声明,在文章页面明显位置给出原文连接
如果文中有什么错误,欢迎指出。以免更多的人被误导。
出处:https://www.cnblogs.com/IwishIcould/
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,或者关注博主,在此感谢!
万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主(っ•̀ω•́)っ✎⁾⁾!
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!

支付宝

微信
如果文中有什么错误,欢迎指出。以免更多的人被误导。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 分享4款.NET开源、免费、实用的商城系统
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库