我的 onClick 不是在点击时触发,而是在页面加载时触发。相关代码如下:
应用程序.js
callAPI(x) {
fetch("http://localhost:8080/" + x)
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }))
.catch(err => err);
}
render() {
<Button
onClick={this.callAPI('api')}
type="success"
className="input-lg">
Search
</Button>
按钮组件:
import React from "react";
function Button({ type = "default", className, children, onClick }) {
return (
<button onClick={onClick} className={["btn btn-lg", `btn-${type}`,
className].join(" ")}>
{children}
</button>
);
}
export default Button;
非常感谢任何帮助!
最佳答案
改变
<Button onClick={this.callAPI('api')} type="success" className="input-lg">
Search
</Button>
至
<Button onClick={() => this.callAPI('api')} type="success" className="input-lg">
Search
</Button>
您将在设置 Prop 后立即调用该函数,而不是在单击该 Prop 时调用该函数。要让该函数在单击时触发,您需要传入一个尚未调用的函数。
关于javascript - React 按钮组件 onClick() 在页面加载时触发,而不是 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55460545/