简体   繁体   中英

calling method on sub component in React functional component via ref

I'm using syncfusion react controls to add some functionality to my app. I want to call a method on the control in my functional component, but I haven't been able to get the ref set properly:

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;

this always throws an error that Cannot read property 'showPopup' of null -- how do you set the ref for the instance of the AutoCompleteComponent so that you can call methods on it?

We can get the reference for the AutoComplete when it's rendered as a functional component with help of using useRef method instead of createRef method. Please find the modified sample from below.

Sample Link : https://codesandbox.io/s/throbbing-shadow-ddsmf

Regards,

Berly BC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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