【问题标题】:calling method on sub component in React functional component via ref通过 ref 在 React 功能组件中的子组件上调用方法
【发布时间】:2020-11-10 20:10:45
【问题描述】:

我正在使用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 以便你可以调用它的方法?

【问题讨论】:

  • 想知道是否将useEffect(() =&gt; {..}, [searchString, listobj.current])ref 传递给useEffect,然后在fetch 之前检查if (listObj.current) 是否可以解决问题? ref 开始时为 null,直到它被设置,所以如果 searchString 被更改,useEffect 将被调用,但 ref 可能仍然为 null?
  • 在功能组件中,您需要useRef,而不是createRef。使用 createRef 会在每次渲染时为您提供一个新的引用,它不会被保留。

标签: javascript reactjs syncfusion react-ref


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多