useImperativeHandle报错:Cannot add property current, object is not extensible
问题原因及解决方案
你的错误是因为子组件中forwardRef的回调函数参数顺序错误:forwardRef的回调第一个参数是组件的props,第二个才是传递进来的ref。你现在把第一个参数当成了ref,实际上拿到的是props——而React的props是不可扩展的冻结对象,当useImperativeHandle尝试给这个“ref”(实际是props)添加current属性时,就会抛出“Cannot add property current, object is not extensible”的错误。
修正后的子组件代码
import { forwardRef, useState, useImperativeHandle } from 'react'; const Toast = forwardRef((props, ref) => { // 需接收props和ref两个参数,顺序不能错 const [openToast, setOpenToast] = useState(true); useImperativeHandle(ref, () => ({ show() { alert("hello"); }, })); return ( <div></div> ); }); export default Toast;
父组件代码无需修改
你的父组件写法是正确的,修正子组件后,点击按钮就能正常调用toastRef.current.show()方法。
内容的提问来源于stack exchange,提问作者mates247
相关产品推荐
相关产品推荐

