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

时间:2020-11-10 20:10:45

标签: javascript reactjs syncfusion react-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实例的引用,以便可以在其上调用方法?

1 个答案:

答案 0 :(得分:0)

我们可以通过使用 useRef 方法而不是 createRef 方法来获取将AutoComplete呈现为功能组件的参考。请从下面找到修改后的示例。

示例链接https://codesandbox.io/s/throbbing-shadow-ddsmf

此致

卑诗省