React函数组件中如何通过ref正确绑定syncfusion AutoComplete调用方法
问题根因
你遇到的Cannot read property 'showPopup' of null报错,是三个实现错误叠加导致的:
- 函数组件中错误使用
createRef()创建ref:createRef是为类组件设计的ref创建API,类组件的实例不会随重渲染销毁,ref对象可以保持长期关联。但在函数组件中,每次状态更新触发重渲染时,都会重新执行函数体里的createRef()生成全新的ref实例——第一次渲染时绑定到AutoCompleteComponent上的旧ref,和后续渲染时代码里引用的新ref根本不是同一个对象,导致ref永远关联不到真实组件实例。 - 调用实例方法前没有做空值校验:当组件挂载未完成、或ref被重渲染重置时,
listObj.current本身就是null,直接访问其上的showPopup方法就会抛出读取属性错误。 - 异步请求逻辑书写错误:把
response.map直接作为fetch的then回调传入,根本没有正常拿到接口返回的数据,连带ref调用逻辑也错位执行。
正确修复方案
- 替换ref的创建方式:函数组件中需要跨渲染保持引用的ref,必须用React提供的
useRef()Hook创建。useRef会在组件全生命周期保持同一个对象引用,不会因为重渲染被重置,能正确绑定Syncfusion的AutoComplete组件实例。 - 调用实例方法时增加空值保护:用可选链
?.判断ref绑定的实例存在后,再调用showPopup方法,避免实例未就绪时报错。 - 修正fetch链式调用逻辑:先在第一个then里解析响应为JSON,再执行数据映射、状态更新和实例方法调用的流程。
修正后的核心实现参考:
// 导入useRef替换原createRef引用 import React, { useRef, 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([]); // 用useRef创建可跨重渲染保持引用的ref实例 const listObj = useRef(null); 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(res => res.json()) .then(response => { // 空值保护后再调用组件方法 listObj.current?.showPopup(); const processedList = response.map((result) => { return { id: result.contactId, label: result.firstName + ' ' + result.lastName } }) setItems(processedList); }) }, [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;
补充说明:Syncfusion的React组件会把所有公开方法直接挂载到ref绑定的实例上,通过useRef正确绑定后,即可直接调用showPopup、hidePopup、focusIn这类内置方法,不需要额外做类型转换。
内容的提问来源于stack exchange,提问作者user101289
相关产品推荐
相关产品推荐

