尝试使用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>
);
}
}
答案 0 :(得分:2)
email
和onDelete
不在handleClick
函数的范围内。您可以将它们作为参数传递。
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>
);