簡體   English   中英

將onClick事件傳遞給React中的Button組件

[英]Pass onClick event to Button Component in 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>
    );
  }
}

emailonDelete不在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>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM