table 列中的按钮不等待 onClick 事件
Button in table column doesn't wait for the onClick event
我有一个 table,其中最后一列应该用作 "delete item" 按钮。 Table 看起来像这样:
const columns = ({ onClick }) => [
{
key: 'type',
onRender: (item) => (
<p className="ms-font-m mb-0">
{item.type}
</p>
),
},
{
key: 'remove',
onRender: (item) => (
<PrimaryButton onClick={onClick(item.type)}>
<FormattedMessage {...messages.removeLight}/>
</PrimaryButton>
),
},
]
const Table = ({ data, onClick, intl}) => (
<Table
items={data}
compact
columns={columns({ onClick })}
/>
);
,其中 onClick 事件调用重写当前状态并设置新状态的函数,如下所示:
handleRemove = (type) => {
const { form } = this.state
var itemsNew = form.items.filter(e => e.type !== type),
this.setState({
form: itemsNew,
});
}
问题是,当呈现 table 时,会立即调用 handleRemove
函数,而不是等待点击事件。但是,如果我删除 item.type
参数并将 handleRemove
作为空函数调用,仅包含一些 console.log(...)
行,它就可以正常工作。
我是 JS 的新手,真的不明白我在这里错过了什么。
只需更改此行
<PrimaryButton onClick={onClick(item.type)}>
至 <PrimaryButton onClick={() => onClick(item.type)}>
另一个解决方案是将函数 'shape' 从 handleRemove = (type) => {...}
更改为 handleRemove = (type) => () => {...}
我有一个 table,其中最后一列应该用作 "delete item" 按钮。 Table 看起来像这样:
const columns = ({ onClick }) => [
{
key: 'type',
onRender: (item) => (
<p className="ms-font-m mb-0">
{item.type}
</p>
),
},
{
key: 'remove',
onRender: (item) => (
<PrimaryButton onClick={onClick(item.type)}>
<FormattedMessage {...messages.removeLight}/>
</PrimaryButton>
),
},
]
const Table = ({ data, onClick, intl}) => (
<Table
items={data}
compact
columns={columns({ onClick })}
/>
);
,其中 onClick 事件调用重写当前状态并设置新状态的函数,如下所示:
handleRemove = (type) => {
const { form } = this.state
var itemsNew = form.items.filter(e => e.type !== type),
this.setState({
form: itemsNew,
});
}
问题是,当呈现 table 时,会立即调用 handleRemove
函数,而不是等待点击事件。但是,如果我删除 item.type
参数并将 handleRemove
作为空函数调用,仅包含一些 console.log(...)
行,它就可以正常工作。
我是 JS 的新手,真的不明白我在这里错过了什么。
只需更改此行
<PrimaryButton onClick={onClick(item.type)}>
至 <PrimaryButton onClick={() => onClick(item.type)}>
另一个解决方案是将函数 'shape' 从 handleRemove = (type) => {...}
更改为 handleRemove = (type) => () => {...}