通过 ref 调用 React 功能组件中子组件的方法

calling method on sub component in React functional component via ref

我正在使用 syncfusion React 控件向我的应用添加一些功能。我想在我的功能组件中的控件上调用一个方法,但我无法正确设置 ref

import React, {createRef, useEffect, useState} from "react";
import {AutoCompleteComponent} from "@syncfusion/ej2-react-dropdowns";
import "@syncfusion/ej2-base/styles/bootstrap.css";
import "@syncfusion/ej2-react-inputs/styles/bootstrap.css";
import "@syncfusion/ej2-react-dropdowns/styles/bootstrap.css";

const UserLookup = ({userSelected}) => {
    const [searchString, setSearchString] = useState('');
    const [items, setItems] = useState([]);
    const helper = new QueryHelper();
    let listObj = createRef();

    const searchStringChanged = (args) => {
        console.log(args.text);
        if (args.text.length > 3) {
            setSearchString(args.text);
        }
    }

    const optionSelected = (event) => {
        memberSelected(event.item.id);
    }

    useEffect(() => {
        fetch('http://example.com/myendpoint')
          .then(response.map((result) => {
                            listObj.current.showPopup(); // <-- this method should be called on the autocomplete component
                            return {
                                id: result.contactId,
                                label: result.firstName + ' ' + result.lastName
                            }
                        }))
          .then(data => console.log(data));
    }, [searchString]);

    return (
        <AutoCompleteComponent
            id="user_search"
            autofill={true}
            dataSource={items}
            fields={
                {
                    value: 'label'
                }
            }
            filtering={searchStringChanged}
            select={optionSelected}
            popupHeight="250px"
            popupWidth="300px"
            placeholder="Find a contact (optional)"
            ref={listObj}
        />
    );
};

export default UserLookup;

这总是会引发错误 Cannot read property 'showPopup' of null -- 如何为 AutoCompleteComponent 的实例设置 ref 以便您可以在其上调用方法?

我们可以在使用 useRef 方法而不是 createRef 方法的帮助下将其呈现为功能组件时获取对自动完成的引用.请从下面找到修改后的示例。

样本Linkhttps://codesandbox.io/s/throbbing-shadow-ddsmf