您的位置:首页 > Web前端 > React

React数据通信父传子和子传父的使用

2022-06-05 15:49 3391 查看

组件中的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'))

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: