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

React问题:按钮onClick无法调用void数组中的方法

问题排查与修复

核心问题分析

  1. 函数立即执行导致返回值丢失:在Navbar.tsx中,传递buttonAction={() => [redirect(), redirect2()]}时,redirect()和redirect2()会被立即调用,返回的是函数执行后的void结果,而非函数本身。这导致buttonAction返回的数组里都是void,无法在点击时触发预期行为。
  2. 类型定义错误:Popup.tsx中buttonAction的类型定义为() => void[],但实际上它应该返回函数数组,而非void数组。
  3. 点击事件未正确调用函数:当前代码中onClick={() => {value}}只是引用了value,没有执行它,需要改为主动调用函数。

修复后的代码

Navbar.tsx

<div className="items">
  <Popup 
    show={true} 
    title="Popup" 
    buttonText={["Button1","Button2"]} 
    buttonAction={() => [redirect, redirect2]} {/* 传递函数引用,不立即执行 */}
  >
  </Popup>
</div>

Popup.tsx

import React from "react";

//styled
import {Area} from "./index.styled"

import Button from "../button";

type Props = {
    show: boolean;
    title?: string;
    desc?:string;
    buttonText:string[];
    buttonAction: () => (() => void)[]; // 更新类型为函数数组
}

const Popup: React.FC<Props> = (props) => {
    if (!props.show) return null;
    // 提前获取函数数组,避免重复调用buttonAction()
    const actions = props.buttonAction();
    return (
        <Area>
            <div className="content">
                {props.title && <h3 className="title">{props.title}</h3>}
                {props.desc && <p className="desc">{props.desc}</p>}
                <>
                    {actions.map((action, index) => {
                        return(
                            <Button 
                                primary 
                                key={index} 
                                onClick={() => action()} // 执行对应的函数
                            >
                                {props.buttonText[index]} {/* 使用传入的按钮文本而非索引 */}
                            </Button>
                        )
                    })}
                </>
            </div>
        </Area>
    )
}

export default Popup;

额外优化建议

  • 避免使用index作为key,如果按钮文本唯一,可以用props.buttonText[index]作为key,更符合React最佳实践。
  • 提前调用props.buttonAction()并赋值给变量,避免在渲染循环中重复执行,提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:06:16