javascript - 将 onClick 事件传递给 React 中的按钮组件
问题描述
尝试使用 Button 组件,但 onClick 似乎无法使用它。如何将方法传递给 Button 组件?
如果我使用标准,onClick 有效。
onClick 在这里什么都不做。
子组件
const buttonStyleDelete = {
backgroundColor:'red'
}
const handleClick = (e) => {
e.preventDefault()
axios.delete("/api/emails/delete/", {
data: {email: email}
}).then(() => onDelete())
}
const EmailItem = ({email, onDelete}) => (
<div>
<h3>{email}</h3>
<Button
onClick={(e) => handleClick(e)}
buttonStyle={buttonStyleDelete}
buttonLabel={'Delete'}
>
Remove
</Button>
</div>
)
父组件
hideEmail = () => this.fetchEmails()
fetchEmails = () => {
fetch("/api/emails/")
.then(res => res.json())
.then(parsedJSON => parsedJSON.map(emails => ({
email: `${emails.email}`,
id: `${emails.id}`
}))).then(emails => this.setState({allEmails: emails}))
}
render() {
return (
<div>
<h2>Admin Page</h2>
<div>
{this.state.allEmails.map((email) => {
return <EmailItem
key={email.id}
email={email.email}
onDelete = {() => this.hideEmail()}/>
})}
</div>
</div>
);
}
}
解决方案
email
and onDelete
are not in scope in the handleClick
function. You could pass them in as arguments instead.
const buttonStyleDelete = {
backgroundColor: "red"
};
const handleClick = (e, email, callback) => {
e.preventDefault();
axios
.delete("/api/emails/delete/", {
data: { email: email }
})
.then(() => callback());
};
const EmailItem = ({ email, onDelete }) => (
<div>
<h3>{email}</h3>
<Button
onClick={e => handleClick(e, email, onDelete)}
buttonStyle={buttonStyleDelete}
buttonLabel={"Delete"}
>
Remove
</Button>
</div>
);
推荐阅读
- r - 在ggplot2中缩小图形时将标签保持在固定距离
- html - 内部带有 iframe 的详细信息元素
- java - 我正在尝试使用 PDF Box 加载 PDF,但是 PDF 无法打开。我不确定我的代码有什么问题
- itext7 - 生成的 PDF 粗体文本看起来很模糊。放大时看起来很精确
- excel - 带有数组参数的 SUM 和 SUMIF
- python - Altair - 条形图中缺少操作按钮
- scala - 是否可以在包对象中进行最大规模的发现?
- java - 在 Spring Boot 服务层的单元测试中模拟原始字符串
- sql - 评估每一行的随机函数
- java - 光标数组进入 ListView 但多列