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

React中使用按钮数组:如何在点击事件中获取按钮标签p.name

How to Get the Corresponding Product Name on Button Click in React

Hey there! Let's fix this issue you're having with accessing the product name when clicking your buttons. The core problem here is that var is function-scoped, so by the time your onClickFunction runs, the p variable will have already been updated to the last item in your Products array. Here are a few straightforward, React-friendly solutions:

1. Use const/let with Arrow Functions to Pass the Product Name Directly

Switch from var to const (or let) for block-level scoping, and wrap your click handler in an arrow function to pass the specific product name as an argument:

const myButtons = []; 
for (const p of Products) {
  const button = (
    <button 
      style={someStyle} 
      onClick={() => onClickFunction(p.name)}
    >
      {p.name}
    </button>
  );
  myButtons.push(button);
}

Then your onClickFunction can accept the name directly:

function onClickFunction(productName) {
  console.log("Clicked product:", productName);
  // Do whatever you need with the name here
}

2. Use a Custom Data Attribute to Store the Product Name

You can attach a custom data-* attribute to each button, then retrieve its value from the event object in your click handler:

const myButtons = [];

// Define your click handler to read from the event target
function onClickFunction(event) {
  const productName = event.target.dataset.name;
  console.log("Clicked product:", productName);
}

for (const p of Products) {
  const button = (
    <button 
      style={someStyle} 
      onClick={onClickFunction}
      data-name={p.name}
    >
      {p.name}
    </button>
  );
  myButtons.push(button);
}

Instead of a for loop, use map() to generate your button array—this is the more idiomatic way to render lists in React, and it naturally handles scoping for you. Don't forget to add a unique key prop (use a product ID instead of index if possible):

const myButtons = Products.map((product) => (
  <button 
    key={product.id} // Critical for React's list rendering optimization
    style={someStyle} 
    onClick={() => onClickFunction(product.name)}
  >
    {product.name}
  </button>
));

Quick Note on var

If you stick with var, you'll run into scoping issues because all iterations of the loop share the same p variable. Even if you tried to store p.name in a separate var inside the loop, it would still end up pointing to the last product's name. So always use const or let in modern JavaScript/React code!

内容的提问来源于stack exchange,提问作者Jose Cabrera Zuniga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:24:08