【问题标题】:Using an Array of buttons in React在 React 中使用按钮数组
【发布时间】:2018-08-28 12:06:22
【问题描述】:

在反应中我有这样的代码:

 var myButtons=[];
 /*Products is an array of objects where each object identify a product*/
 for (var p of Products) {
     var button = <button 
                       style={someStyle}
                       onClick={onClickFunction}>
                       p.name
                  </button>
     myButtons.push(button)
 }

我将在渲染命令上使用这个反应按钮数组。我遇到的问题是我不知道如何使这些按钮之一通过 onClickFunction 显示其标签 p.name。

【问题讨论】:

  • 函数可以接受参数
  • 所以,我应该使用: var button =
  • 您绝对可以这样做,但是,我建议您颠倒您的逻辑。您正在迭代产品,但调用一个返回 &lt;button&gt; 的函数,以便您可以执行以下操作:&lt;div&gt;{Products.map(makeButton, this)}&lt;/div&gt; 这会将数据变量传递到回调中。干净多了

标签: javascript reactjs button jsx


【解决方案1】:

最简单的方法是使用 ES6 语法和数组map
name 属性应该是唯一的,不要忘记为每个按钮提供一个键:

const myButtons = Products.map(p => (
  <button style={someStyle} onClick={e=>{ this.onClickFunction(e, p.name); }} key={p.name}/>
    {p.name}
  </button>
));

使用箭头函数,因此不需要.bind(this)。如果按钮位于 form 中,请添加 e.preventDefault() 以防止默认行为。

onClickFunction = (e, name) => {
  e.preventDefault();
  // Your button behavior goes here.
}

【讨论】:

    【解决方案2】:

    一种更简单更用户友好的方法是使用函数迭代数据。 (请注意,这没有考虑范围,因此如果它在组件内部,则可能需要this

    function makeButton(data) {
        return (
            <button 
                style={someStyle}
                onClick={() => onClickFunction(data.label)}> //pass parameter for callback here if binding isn't used
                data.name
            </button>
        );
    }
    

    现在您可以在 div 中简单地使用绑定映射!

    <div>
        {Products.map(makeButton, this)}
    </div>
    

    【讨论】:

      【解决方案3】:

      您可以将标签添加为参数:

      <button style={someStyle} onClick={p.name => onClickFunction(p.name)}>
          p.name
      </button>
      

      还有:

      onClickFunction = (label) => () =>{
          console.log(label)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-01
        • 2019-10-18
        • 2019-08-05
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2021-08-05
        • 2021-09-10
        相关资源
        最近更新 更多