You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reactjs-Popup报Cannot read properties of undefined (reading 'forwardRef')如何解决

解决方案

1. 修复Cannot read properties of undefined (reading 'forwardRef')报错

该报错由React导入语法错误导致,你当前使用了命名导入引入React,而React是默认导出模块,修改导入语句即可:

// 错误写法
import { React, useState } from "react";
// 正确写法
import React, { useState } from "react";

2. 实现Popup与自定义CustomButton的状态同步

需要做两处调整:

  • 将CustomButton组件移到TextInput组件外部,避免每次TextInput渲染重复创建组件
  • Popup的trigger回调会接收open状态和绑定用的ref,需要把两个参数都传给CustomButton,才能实现点击触发、状态同步的效果

修正后的完整代码

import React, { useState } from "react";
import { useField } from "formik";
import { StyledTextInput, StyledLabel, StyledIcon, ErrorMsg } from "./Styles";
import { FiEyeOff, FiEye } from "react-icons/fi";
import Popup from "reactjs-popup";

// 将CustomButton移到组件外部
const CustomButton = React.forwardRef(({ open, ...props }, ref) => (
  <button className="button" ref={ref} {...props}>
    Trigger - {open ? "Opened" : "Closed"}
  </button>
))

export const TextInput = ({ icon, ...props }) => {
  const [field, meta] = useField(props);
  const [showpass, setShowpass] = useState(false);

  return (
    <div style={{ position: "relative" }}>
      <StyledLabel htmlFor={props.name}>{props.label}</StyledLabel>
      {props.type !== "password" && (
        <StyledTextInput
          invalid={meta.touched && meta.error}
          {...field}
          {...props}
        />
      )}
      {props.type === "password" && (
        <StyledTextInput
          invalid={meta.touched && meta.error}
          {...field}
          {...props}
          type={showpass ? "text" : "password"}
        />
      )}
      <StyledIcon>{icon}</StyledIcon>
      {props.type === "password" && (
        <StyledIcon onClick={() => setShowpass(!showpass)} right>
          {showpass && <FiEye />}
          {!showpass && <FiEyeOff />}
        </StyledIcon>
      )}
      {meta.touched && meta.error ? (
        <ErrorMsg>{meta.error}</ErrorMsg>
      ) : (
        <ErrorMsg style={{ visibility: "hidden" }}>.</ErrorMsg>
      )}
      
      <Popup
        // trigger回调接收open状态和ref,全部传给CustomButton
        trigger={({ open, ref }) => <CustomButton open={open} ref={ref} />}
        position="right center"
        closeOnDocumentClick
      >
        <span> Popup content </span>
      </Popup>
    </div>
  );
};

内容的提问来源于stack exchange,提问作者Guilherme Cavenaghi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:27:03