【发布时间】: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(() => {..}, [searchString, listobj.current])和ref传递给useEffect,然后在fetch之前检查if (listObj.current)是否可以解决问题?ref开始时为 null,直到它被设置,所以如果 searchString 被更改,useEffect 将被调用,但 ref 可能仍然为 null? -
在功能组件中,您需要useRef,而不是
createRef。使用createRef会在每次渲染时为您提供一个新的引用,它不会被保留。
标签: javascript reactjs syncfusion react-ref