【问题标题】:React: passing parameters to a function in mapReact:将参数传递给地图中的函数
【发布时间】:2017-12-09 21:38:46
【问题描述】:

我正在构建一个组件,该组件使用 MaterialDesign 的表在 React 中显示用户数组。

每一行都由一个 map 函数生成:

let actions = this.props.rowButtons;
...
{this.props.tableData.map( (val, index) => (
                       <TableRow key={index}>
                         <TableRowColumn >{index}</TableRowColumn>
                         <TableRowColumn >{val.firstName}</TableRowColumn>
                         <TableRowColumn >{val.lastName}</TableRowColumn>
                         <TableRowColumn >{val.email}</TableRowColumn>
                         <TableRowColumn >
                            <ActionButtons actions={actions}/>
                         </TableRowColumn>
                       </TableRow>
))}

&lt;ActionButtons&gt; 组件创建一个或多个按钮,并将对象数组作为参数,例如[{type: string, onClick: function}, {type: string, onClick: function}, ... ](数组中每个对象一个按钮); 父组件在 this.props.rowButtons 中发送这样一个数组。

我想将 val 作为参数传递给每个 onClick 函数以获得类似

actions = [{type: "personButton", onClick: onClick(val)}, {type: '', onclick: someOtherfunction(val)}]; 

【问题讨论】:

  • 试试onClick: () =&gt; onClick(val)
  • 我不太明白。我将对象数组分配给“动作”。我想将 val 注入这个数组中的每个函数

标签: javascript reactjs parameters map-function


【解决方案1】:

您必须稍微修改actions。试试下面的方法。

modifyActions = (actions, val) => {
  return actions.map((a) => {
      return Object.assign({}, a, {onClick: () => a.onClick(val)})
  })
}

<ActionButtons actions={this.modifyActions(actions, val)})}/>

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2018-11-12
    • 1970-01-01
    • 2012-07-30
    • 2021-11-24
    相关资源
    最近更新 更多