首页 > 解决方案 > 使用 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);应该得到子组件对象时。

标签: javascriptreactjsgraphqlreact-apolloapollo-client

解决方案


推荐阅读