繁体   English   中英

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

[英]calling method on sub component in React functional component via ref

我正在使用syncfusion反应控件向我的应用程序添加一些功能。 我想在我的功能组件中调用控件上的方法,但我无法正确设置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方法的帮助下,我们可以在将 AutoComplete 呈现为功能组件时获取它的引用。 请从下面找到修改后的样本。

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

问候,

卑诗省伯利

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM