首页 > 其他分享 >解决React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Di

解决React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Di

时间:2024-09-19 11:47:01浏览次数:1  
标签:Function access const useImperativeHandle open React forwardRef ref

问题

当我使用如下方式调用组件子组件UploadModal并且绑定Ref时React报错“Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?”;

const UploadModalRef = useRef(null);
const openUploadModal = () => {
 UploadModalRef.current.open();
}
// ...
<UploadModal ref={UploadModalRef} />

然而当我按照报错提示使用forwardRef包裹子组件UploadModal后依然报错“TypeError: Cannot read properties of null (reading 'open')”无法访问子组件的方法。

解决:

通过useImperativeHandle暴露子组件方法

import { forwardRef, useState, useImperativeHandle } from "react";

export default forwardRef(function UploadModal(props, ref) {
    const [Visible, setVisible] = useState(false);
    
    const 
        open = () => setVisible(true),
    ;

    useImperativeHandle(ref, () => {
        return {
            open,
        }
    })

    return (
        //...
    )
})

useImperativeHandle 是 React 中的一个 Hook,它能让你自定义由 ref 暴露出来的句柄。https://zh-hans.react.dev/reference/react/useImperativeHandle

标签:Function,access,const,useImperativeHandle,open,React,forwardRef,ref
From: https://www.cnblogs.com/facingscreen/p/18420288

相关文章

  • react react18+vite+typeScript+eslint+prettier+husky+lint-staged+commitlint 快速
    技术栈react18react-router6antd5zustand4vite45axiosfakerjs模拟数据dayjslodashtypescriptechartscommitlint、prettier、eslinthusky、lint-staged自定义commitlint、cz-cli自定义eslint、prettier代码规范技术栈代码格式规范和语法检测vscode:统一前端编辑器。editor......
  • react hooks--useCallback
    概述useCallback缓存的是一个函数,主要用于性能优化!!!基本用法如何进行性能的优化呢?useCallback会返回一个函数的memoized(记忆的)值;在依赖不变的情况下,多次定义的时候,返回的值是相同的;语法:constmemoizedCallback=useCallback(()=>{doSomething(a,b);......
  • ZBLOG PHP提示"Call to undefined function mysql_connect()"错误
    当遇到Z-BlogPHP在PHP7.2上出现 mysql_connect() 未定义的错误时,这是因为PHP7.2默认不再支持MySQL扩展(mysql 扩展)。你需要进行一些调整来使Z-BlogPHP兼容PHP7.2。以下是两种解决方案:解决方案一:降级PHP版本如果你暂时不想修改代码,可以选择降级PHP版本到一......
  • zblogPHP后台在线升级后提示Call to undefined function Redirect_cmd_end()错误
    当Z-BlogPHP在线升级后提示“CalltoundefinedfunctionRedirect_cmd_end()”错误时,这通常是因为升级过程中某些文件没有正确更新或存在兼容性问题。以下是一些可能的解决步骤:1.检查函数定义问题描述:Redirect_cmd_end() 函数可能未被定义。解决方法:打开Z-BlogPHP......
  • react是什么?
    React是一个由Facebook开发和维护的开源JavaScript库,用于构建用户界面,特别是单页应用程序(SPA)。它通过组件化的方式来帮助开发者创建可重用的UI组件,从而简化了前端开发的复杂度。React的核心特点包括:核心特点React是一个强大的工具,用于构建动态和高效的用户界面。通过组......
  • nn.Dropout()与nn.functional.dropout()的区别
    在PyTorch中,`Dropout`主要有两种常见的使用方式:1.**`torch.nn.Dropout`模块**:通常用于模型的层定义中。2.**`torch.nn.functional.dropout`(即`F.dropout`)**:通常用于在`forward`方法中直接调用。###1.**`torch.nn.Dropout`**这是PyTorch中的标准`Dropout`层,通......
  • HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed
    问题描述:HTTPError500.19-InternalServerErrorTherequestedpagecannotbeaccessedbecausetherelatedconfigurationdataforthepageisinvalid.DetailedErrorInformation:Module IISWebCoreNotification BeginRequestHandler Notyetdete......
  • Call to undefined function think\exception\config()
    错误信息 Calltoundefinedfunctionthink\exception\config() 表示在ThinkPHP框架中调用了未定义的函数 think\exception\config()。这通常是由于以下几个原因造成的:命名空间问题:可能是命名空间声明不正确或导入了错误的类。配置文件问题:可能是配置文件未正确加载或存在......
  • CF1334F Strange Function 题解
    传送门定义一个函数\(f\),输入一个数组\(a\),输出一个数组\(b\)为\(a\)的子序列:\(b_1=a_1\),设\(b_i\)在\(a\)中的位置为\(pos_i\),则\(b_i\)为\(a_{pos_{i-1}+1}\sima_n\)中第一个严格大于\(b_{i-1}\)的数。\(n\le5\times10^5\),\(|p_i|\le10^9,1\lea_i,b_i\le......
  • Scala学习之旅-魔幻的PartialFunction
    聊点什么今天我们来聊聊Scala中的PartialFunction,以及collect与PartialFunction的完美结合PartialFunction的定义只接受一个参数只处理输入数据中的一部分可以定义一个isDefinedAt方法,来定义可以处理的输入数据中的哪一部分,和apply方法一个PartialFunction......