我有两个初始状态:
element_array: [],
element_items: {
element_type: "",
element_name: ""
},
表单接受输入并更新 element_items
的状态,然后我从那里将 element_items
连接到 element_array
使用:
const currentTypeElement = this.state.element_items
this.setState(function (currentState) {
return {
element_array: currentState.element_array.concat([currentTypeElement])
}
});
这很好用,因为我可以在表中映射 element_array
。但我还想在表格行中为每个 element_array
对象添加一个“编辑”按钮。所以我在我的组件中添加了一个函数:
handleElementEdit(prop) {
...
}
在我的 render()
方法中有
<table className="mb-0 table table-hover">
<thead>
<tr>
<th>Element Type</th>
<th>Element Name</th>
</tr>
</thead>
<tbody>
{this.state.element_array.map(function (prop, key) {
return (
<tr key={key}>
<td>{prop.element_type}</td>
<td>{prop.element_name}</td>
<td>
<button onClick={() => this.handleElementEdit(prop)}>Edit</button>
</td>
</tr>
)}
)}
</tbody>
</table>
但是当我点击按钮时它显示错误
TypeError: Cannot read property 'handleElementEdit' of undefined.
onClick
事件应该将 prop 传递给 handleElementEdit
函数。
我不明白为什么会这样。请帮忙。
最佳答案
基本上,当您使用 map 函数时发生的情况 this
的范围仅限于该 map 函数,并且 this.handleElementEdit
将尝试在map
并且因为它,它会抛出错误。
你可以像这样使用箭头函数。
{this.state.element_array.map((prop, key)=> {
return (
<tr key={key}>
<td>{prop.element_type}</td>
<td>{prop.element_name}</td>
<td>
<button onClick={() => this.handleElementEdit(prop)}>
Edit
</button>
</td>
</tr>
)
})}
箭头函数将用于保留父类的范围。
另一种解决方案是,您可以在构造函数中绑定(bind)事件处理程序,例如:
constructor() {
super();
this.handleElementEdit = this.handleElementEdit.bind(this);
}
您也可以使用下面提到的解决方案,例如将 this
作用域存储在变量中并使用该变量绑定(bind)事件。
let that=this;
{this.state.element_array.map(function (prop, key)=> {
return (
<tr key={key}>
<td>{prop.element_type}</td>
<td>{prop.element_name}</td>
<td>
<button onClick={() => that.handleElementEdit(prop)}>
Edit
</button>
</td>
</tr>
)
})}
关于javascript - 如何将参数传递给 map 函数中的事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629586/