Javascript 通过ref调用React功能组件中的子组件的方法
我正在使用Javascript 通过ref调用React功能组件中的子组件的方法,javascript,reactjs,syncfusion,react-ref,Javascript,Reactjs,Syncfusion,React Ref,我正在使用syncfusionreact控件向我的应用程序添加一些功能。我想在我的功能组件中的控件上调用一个方法,但我无法正确设置ref: import React, {createRef, useEffect, useState} from "react"; import {AutoCompleteComponent} from "@syncfusion/ej2-react-dropdowns"; import "@syncfusion/ej2
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;
import React,{createRef,useffect,useState}来自“React”;
从“@syncfusion/ej2 react dropdowns”导入{AutoCompleteComponent}”;
导入“@syncfusion/ej2base/styles/bootstrap.css”;
导入“@syncfusion/ej2/styles/bootstrap.css”;
导入“@syncfusion/ej2 react下拉列表/style/bootstrap.css”;
const UserLookup=({userSelected})=>{
const[searchString,setSearchString]=useState(“”);
const[items,setItems]=useState([]);
const helper=new queryhelp();
让listObj=createRef();
const searchStringChanged=(args)=>{
console.log(args.text);
如果(args.text.length>3){
设置搜索字符串(args.text);
}
}
const options selected=(事件)=>{
已选择成员(event.item.id);
}
useffect(()=>{
取('http://example.com/myendpoint')
.然后(response.map)((result)=>{
listObj.current.showPopup();//console.log(数据));
},[searchString]);
返回(
);
};
导出默认用户查找;
这总是会引发一个错误,即
无法读取null的属性“showPopup”
——如何设置自动完成组件的实例的ref,以便可以对其调用方法?我们可以在使用useRef将自动完成组件呈现为功能组件时获取其引用>方法而不是createRef方法。请从下面查找修改后的示例
示例链接:
问候,
Berly B.C想知道是否将useffect(()=>{..}[searchString,listobj.current])
ref
传递给useffect,然后还检查if(listobj.current)
在获取之前
会起作用吗?ref
开始时为null,直到它被设置,所以如果searchString被更改,将调用useffect,但ref可能仍然为null?在功能组件中,您需要的是,而不是createRef
。使用createRef
将在每次渲染时为您提供一个新的引用,而不是被保存下来。