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

React中动态添加按钮的Hover、onClick功能失效问题求助

问题核心原因

你的按钮点击事件完全没触发,是因为React的事件绑定采用小驼峰命名,你写的OnClick(首字母大写)是无效的,React识别不了这个属性,自然不会绑定点击回调。

完整修复方案

除了修复事件名,还要解决两个潜在问题:

  • 全局的buttonText会导致所有按钮的文本同步变化,应该让每个链接项单独管理自己的按钮状态
  • 复制逻辑需要对应当前项的短链接,而不是依赖全局的copyText

修改后的代码如下:

import React, { useState } from "react";
import Button from "./Button";

function LoadShortenUrl(props){
    // 把每个链接的按钮状态单独存在数组中,索引对应链接的位置
    const [buttonStates, setButtonStates] = useState(
        Array(props.ogLink.length).fill("Copy")
    );

    // 处理复制和按钮文本变化,接收当前索引
    const handleCopyAndUpdateText = (index) => {
        const targetLink = props.shortenLink[index];
        navigator.clipboard.writeText(targetLink)
            .then(() => {
                // 更新对应索引的按钮文本
                const newStates = [...buttonStates];
                newStates[index] = "Copied";
                setButtonStates(newStates);
                console.log("Text Copied");
            })
            .catch(err => {
                console.error("复制失败:", err);
                alert("复制失败,请重试");
            });
    };

    const links = props.ogLink.map((originalLink, index) => (
        <div className="display-url" key={index}>
            <p>{originalLink}</p>
            <a 
                className="shorten-link-position" 
                href={props.shortenLink[index]}
                target="_blank"
                rel="noopener noreferrer"
            >
                {props.shortenLink[index]}
            </a>
            {/* 修复事件名为onClick,传递当前索引,按钮文本用对应状态 */}
            <Button 
                onClick={() => handleCopyAndUpdateText(index)} 
                buttonText={buttonStates[index]} 
                className="submitButton"
            ></Button>
        </div>
    ));

    return <>{links}</>;
}

export default LoadShortenUrl;

关键修改点说明

  1. 事件名修复:将OnClick改为onClick,这是React事件绑定的标准写法
  2. 独立按钮状态:用数组buttonStates存储每个按钮的文本状态,避免多个按钮状态互相干扰
  3. 精准复制逻辑:点击时传递当前链接的索引,直接复制对应位置的短链接,不需要全局的copyText
  4. 错误处理:给navigator.clipboard.writeText添加catch捕获复制失败的情况,提升用户体验
  5. 优化数组遍历:用props.ogLink.map替代Array.from,更符合React中遍历数组生成元素的习惯

另外需要确认你的Button组件内部正确接收并传递了onClick属性,比如Button组件的代码应该类似这样:

// Button.jsx示例
export default function Button({ onClick, buttonText, className }) {
    return (
        <button 
            onClick={onClick} 
            className={className}
        >
            {buttonText}
        </button>
    );
}

如果Button组件没有正确传递onClick属性,即使父组件绑定了事件也不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:35:02