React中使用按钮数组:如何在点击事件中获取按钮标签p.name
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); }
3. Use Array.map() (Recommended React Approach)
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

