javascript - 如何从一个组件调用函数到另一个组件?反应
问题描述
我在 react.js 工作。我创建了一个组件Backend.jsx
。我希望它作为一种服务(如角度)工作,我可以在其中发送 API 请求。我想调用Backend
其他一些组件中的方法。
我在组件中调用了这个后端服务,并尝试发送数据并BackendService
使用道具获取它。
但显然这行不通。
这是我的代码
在组件中:
这将在表单提交后调用。
handleLoginSubmit = (event) => {
event.preventDefault();
console.log(this.state.data);
<BackendService onSendData = {this.state.data} />
}
在后端服务中:
constructor(props) {
super(props);
this.state = { }
this.login(props)
}
login = (props) =>
{
console.log('login', props);
};
任何建议我如何login
在component
. 或任何其他获得服务组件数据的建议。
解决方案
你可以试试这个:
1.Component.js
class Componet extends React.Component {
constructor(props) {
super(props);
this.state={
data:"this state contain data"
}
this.backendServiceRef = React.createRef(); // Using this ref you can access method and state of backendService component.
}
render() {
return (
<div className="App">
<button onClick={() => {
this.backendServiceRef.current.login()
}}>click</button>
<BackendService ref={this.backendServiceRef} onSendData = {this.state.data}></BackendService>
</div>
);
}
}
export default Componet;
2.后端服务.js
class BackendService extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
login = (props) => {
alert("login call")
};
render() {
return (
<div>
Backend service component
</div>
)
}
}
推荐阅读
- xmp - 使用 libexif 保留/复制 XMP
- python - 如何在日期时间索引数据框中选择特定周并绘制它们的平均值
- node.js - 如何不仅在第一次应用过滤器,而且在持续的对话交互中也应用过滤器?
- php - 如何使用 Bootstrap 进行相等的垂直间隔和居中划分
- python - 烧瓶 SQLAlchely UPDATE 而不是 INSERT
- android - Firebase 多应用项目无法从 GooglePlay 控制台获取有关应用内购买的信息
- javascript - 角度保存编辑的内容
- android - 在android中仅保存pdf的第一页的多页pdf
- cloud - 在 Git Hub 操作中运行赛普拉斯时连接的 ARM 设备
- python - 如何使使用 Python 请求库的 GET 请求永远不会导致程序失败?