首页 > 解决方案 > 如何在反应中将两个函数传递给onClick事件

问题描述

我想将两个函数传递给onClickevent which ishandleSubmit和from handleDeletetheHomePage.jsHomeItem.js

这是我的错误: No duplicate props allowed react/jsx-no-duplicate-props.

这是我的 HomePage.js:

 const HomePage = props => {
  const tvshow = props.item;
  let res;

  if (tvshow.length > 0) {
    res = tvshow.map(res=> (
      <Content item={res} onClick={props.onClick}/>
    ));
  }

  return (
    <div>
      <Container>
        <Row>{res}</Row>
      </Container>
    </div>
  );
};

export default HomePage;

这是我的 HomeItem.js:

const HomeItem = props => {
  function handleSubmit() {
    props.onClick({
      name: props.item.name,
      id: props.item.id
    });
  }

  function handleName() {
    props.onClick({
      name: props.item.name
    });
  }

<Button onClick={handleSubmit}></Button>
<Button onClick={handleName}></Button>

这是我的 App.js:

handleSubmit(newFavorite) {}
handleName(newFavorite) {}

render() {
  <Route
    exact
    path="/"
    render={() => (
      <HomePage
        item={this.state.SaveFavorite}
        onClick={this.handleSubmit}
        onClick={this.handleName}
      />
    )}
  />
} 

所以我的问题是如何将 2 onClick 函数放到 Hompage.js

标签: javascriptreactjs

解决方案


这个怎么样:

<HomePage
        item={this.state.SaveFavorite}
        onClick={(favorite)=>{
            this.handleSubmit(favorite);
            this.handleName(favorite);
            }
        }
        />

这假设您的目标是一次调用两个函数。如果它们应该在不同的情况下被调用,请给一个函数一个不同的名称,例如onSubmitor onNameChange


推荐阅读