学习目标:
提示:组件之间传值
例如:
- 十分钟掌握组件之间传值
学习内容:
提示:学会组件之间传值
(3)组件之间传值
解决方案:事件中心
核心技术:第三方事件模块events
—>执行命令安装第三方依赖-- npm install events -S
事件中心:src/views/utils/eventsplugin.js
// 引入依赖
import Events from "events";
// 导出事件对象
export default new Events()
组件Child.jsx
发送数据
import React, {Component} from 'react';
import './Child.css'
import events from "../../utils/eventsplugin";
class Child extends Component {
state = {
dataFromChild: "子组件数据999",
dataToOther: "要传递给其他组件的值2023"
}
// 发送给父组件
send() {
// 调用父组件函数,完成数据传递
// 可以通过自定义属性this.props.sendData()调用父组件getData()函数,完成数据传递
this.props.sendData(this.state.dataFromChild)
}
// 通过事件中心发送数据 --自定义事件,用来发送事件
sendOther() {
events.emit("dat-transfer", this.state.dataToOther)
}
render() {
// 接收父组件传递的参数
const {msg, info} = this.props
// console.log(this.props, "this.props 当前组件的所有属性")
return (
<div className="child-container">
<h2>子组件</h2>
<p>来自父组件的数据:{msg}</p>
<p>来自父组件的信息:{info}</p>
<br/>
<button onClick={this.send.bind(this)}>发射===》父亲</button>
<button onClick={this.sendOther.bind(this)}>发射数据给===》其他 组件</button>
</div>
);
}
}
export default Child;
组件Other.jsx
接受数据
import React, {Component} from 'react';
import './Other.css'
import events from "../../utils/eventsplugin";
class Other extends Component {
//状态管理数据
state = {
getMsg: "等待接收信息"
}
render() {
// 监听自定义事件, 获取数据
events.on("dat-transfer", (dat) => {
console.log("on2222")
this.setState({
getMsg: dat
})
})
return (
<div className="other-container">
<h2>另一个组件</h2>
<p>接受的数据:{this.state.getMsg}</p>
</div>
);
}
}
export default Other;
将组件Other.jsx
在Parent组件上注册使用
import React, {Component} from 'react';
import './Parent.css'
import Child from "../child/Child";
import Other from "../other/Other";
class MyComponent extends Component {
// 类组件状态数据,保存在state中
state = {
msgFormParent: "父亲要传递的值",
info: "父亲传递的info信息2",
msgFromChild: ""
}
getData(data) {
this.setState({
msgFromChild: data
})
}
render() {
return (
<div className="parent-container">
<h1>组件传值:父组件</h1>
<p>{this.state.msgFormParent}</p>
{/*设置自定义属性msg, 将父组件数据赋值给这个属性*/}
{/*
将声明的getData函数,赋值给子组件的sendData属性
子组件内部this.props.sendData 直接调用 父组件 getData函数
结果:子组件内this.props.sendData和父组件getData是同一个函数
*/}
<Child msg={this.state.msgFormParent} info={this.state.info} sendData={this.getData.bind(this)}/>
<br/>
<h1>等待子组件传递的信息:{this.state.msgFromChild}</h1>
<br/>
<h2>组件--》组件直接传值</h2>
<Other/>
</div>
);
}
}
MyComponent.propTypes = {};
export default MyComponent;