onClick事件在我的React代码中不起作用

时间:2019-01-27 18:29:49

标签: reactjs events

我在render()中有一个onClick事件,该事件不起作用,我已经尝试了(显然不是)所有操作。

我在做什么错了?

render() {

const Card = ({backgroundColor, id, state}) =>{  
    const style = {
        width: '100px',
        height:'100px',
        backgroundColor: backgroundColor,
        key: id,
        state: state,
    }
    return <div style={style} />
}

const finalCards = this.state.cards.map((n) =>(
  <Card backgroundColor={n.hiddenColor} key={n.id} state={n.state} onClick={() => alert('clicked')} />
));

return (
  <div className="App">
      {finalCards}
  </div>
);

}  }

1 个答案:

答案 0 :(得分:2)

由于Card是一个单独的组件,因此应保留它在渲染方法之外进行声明。

但是问题在于,您正在将onClick函数传递给组件,但没有将该onClick函数与HTML元素(在本例中为<div /> )。

这应该有效

const Card = ({backgroundColor, id, state, onClick}) =>{  
    const style = {
        width: '100px',
        height:'100px',
        backgroundColor: backgroundColor,
        key: id,
        state: state,
    }
    return <div style={style} onClick={onClick} />
}