首页 > 解决方案 > 将 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>
    );
  }
}

标签: javascriptreactjs

解决方案


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>
);

推荐阅读