我有一个按钮的onClick
函数,该按钮每秒被调用数百次,没有任何实际的鼠标交互。
constructor(props, context) {
super(props, context);
this.state = {
show: this.props.show,
store: this.props.store,
price: this.props.price,
category: this.props.category,
date: this.props.date,
shown: "inline",
id: this.props.id
};
}
kill = () => {
this.props.kill(this.state.id);
};
render() {
const divStyle = {
padding: "1em",
border: "1px solid black"
};
function trashCanVisible() {}
function trashCanAway() {}
return (
<div display={this.state.shown}>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossOrigin="anonymous"
/>
<Button variant="light">
<Container>
<Row>
<div style={divStyle}>
<Col>
<FontAwesomeIcon icon={faFilePdf} size="8x" />
</Col>
</div>
<Col>
<table>
<thead>{this.state.store}</thead>
<tr>
<td>{this.state.date}</td>
</tr>
<tr>
<tfoot>${this.state.price}</tfoot>
</tr>
<tr>
<td />
</tr>
<tr>
<p>{this.state.category}</p>
</tr>
<tr>
<td>{this.state.description}</td>
</tr>
</table>
</Col>
<Col>
<Button variant="light" onClick={this.kill()}>
<FontAwesomeIcon icon={faTrashAlt} size="1x" />
</Button>
</Col>
</Row>
</Container>
</Button>
</div>
);
}
}
此onClick={this.kill()}
函数引用kill()
函数,该函数是引用父类中pop()
函数的传递函数:
pop(id) {
console.log("pop" + id);
}
我希望底部按钮上的onClick=kill()
功能仅在单击时运行。但是,它一直运行并给出充满"pop1"的控制台输出。
替换
<Button variant="light" onClick={this.kill()}>
跟
<Button variant="light" onClick={this.kill}>
你在初始化期间调用 kill(( 方法,这不是你想要的。您希望在 onClick 方法中传递对该函数的引用,因此仅当 onClick(( 触发时才会调用引用的函数。
将其更改为onClick={() => this.kill()}
,您应该很高兴 👍