javascript - 使用 Apollo 客户端 GraphQL 时如何在父组件中获取 React Js 子组件引用
问题描述
我有两个反应组件,子组件将 Apollo 客户端用于 GraphQL,它将子组件包装为高阶组件。我想使用引用访问子类方法以在父类中执行子方法,但是当我使用 ref 时,我得到 Graphql 对象而不是反应子组件。我的代码示例如下所示。
注意:
这个问题不是
React js change child component's state from parent component
OR
Access child of child from parent component in react
的重复
因为
他们不使用GraphQL Apollo Client)
父组件
import React, {Component} from 'react';
import "./Child";
class Parent extends Component{
state={
};
executeSomeChildFunction = () =>{
/* console.log(this.myChild); */
this.myChild.childFunction();
};
render(){
return(
<div>
<button onclick={this.executeSomeChildFunction}>
Click To Execute Child Function
</button>
<Child ref={el=> this.myChild =el} />
</div>
);
};
}
export default Parent;
子组件
import React, {Component} from 'react';
const myQuery = `query DriversQuery() {
drivers: {
edges{
node{
id
pk
firstName
lastName
}
}
}
}`;
class Child extends Component{
state={
};
childFunction = () => {
alert("I am a child function");
};
render(){
return(
<div>Replace this div with your code!</div>
);
};
}
export default gql(myQuery, {/*some options*/})(Child);
当console.log(this.myChild);
我得到这样的 graphql 对象时,我得到了什么输出。
预期输出
我想获得子元素参考。这样当我console.log(this.myChild);
应该得到子组件对象时。
解决方案
推荐阅读
- unit-testing - 如何使用 jasmine 模拟 window.click(event)
- sql - 在 oracle. 中,替换或引用 reg_exp 中特殊字符的语法是什么,例如 $ 或 @ 或 & 或 |
- sql - 什么是 SQL 中与日期一起使用的“级别”?
- groovy - 在自定义类中使用时出现 Swtbot.syncExec() 问题
- javascript - Reactjs - 未捕获的类型错误:无法读取未定义的属性“then”
- datetime - 默认日期分配失败
- java - 如果另一个应用程序在存储(DB)处更改了数据,如何触发应用程序更新缓存?
- php - 在 Laravel 5.7 上添加日期时间
- python - python regexp 方法返回一个包含空元素的列表
- iis - 智能卡身份验证停止在 IIS 7.5 上工作 - 每个人都得到 401