reactjs - 如何在没有父子关系的情况下将数据从一个组件发送到另一个组件
问题描述
家庭组件
import React, { Component } from 'react';
import Two from 'components/Two.jsx'
import One from 'components/One.jsx'
class Home extends Component {
constructor(props){
super(props)
this.state = {
}
this.one = React.createRef();
}
getData = (data) => {
this.one.current.finalClick(data);
}
render() {
return (
<div>
<Two shareData={this.getData} />
<One ref={this.one} />
</div>
);
}
}
export default Home;
一个组件:
import React from 'react'
class One extends React.Component {
constructor(props){
super(props);
this.state={
}
}
finalClick = (data) => {
console.log(data)
}
render(){
return (
<div>
</div>
)
}
}
export default One;
两个组件:
import React from 'react'
class Two extends React.Component {
handleClick = (data) => {
this.props.shareData(data)
}
render(){
return (
<div>
<br/>
<button className="btn btn-info" onClick={() => this.handleClick('hellow')}>click</button>
</div>
)
}
}
export default Two;
在这里,我试图从另一个组件中单击一个功能。这不是它的父组件或子组件。
首先,我单击两个按钮,它将数据发送到 Home 组件。它正在记录数据。
我想在 Home 组件中调用getData()后同时将数据发送到finalClick()方法。
我在One Component 中的finalClick()函数被点击,但数据没有通过。
解决方案
将要共享的数据保存为Home
. 传递一个函数 from Home
to Two
throughTwo
的 props 以更新数据。将数据从Home
's 状态传递到One
props 中。
推荐阅读
- python - 如何存储一个整数(例如高分),以便在程序关闭后也能保存?
- c# - 如何在 uwp 中使用 ssl 证书
- ios - 登录/注销时如何自动更新 RearViewRevealController 中的 UILabel?
- r - 反应式过滤和添加闪亮
- java - CRON 作业在部署后不按给定的过期时间表执行
- c# - Jquery Unobtrusive Validation 在绑定选项以在 asp.net core razor 页面中动态选择下拉列表后失败
- android - 如果使用相同的 WiFi 网络,我可以与安装在其他手机中的相同应用程序共享 android 一个应用程序数据库吗?
- python - 这是获得二叉树高度的好方法吗?
- python - 如何使用初始数据点将曲线拟合到曲线数据集?
- docker - 从容器中获取 docker 容器 ID 及其主机路径