React组件中PrimaryButton点击无法触发sendConvoc方法问题
React类组件自定义按钮点击不生效修复
问题根因
两处事件绑定都犯了相同的语法错误:箭头函数内仅返回了目标函数的引用,没有实际调用执行函数,导致点击时逻辑完全不触发:
- PlayerList组件中给
PrimaryButton传参时写的onClick={() => this.sendConvoc},箭头函数执行后只会返回sendConvoc函数本身,不会运行函数内部逻辑 - PrimaryButton组件内部给原生button标签绑定事件时写的
onClick={() => this.onClick},存在完全一样的问题,点击后不会调用组件类里定义的onClick方法
另外你的PrimaryButton没有给type属性设置默认值,button默认type为submit,如果放在表单内会意外触发表单提交行为。
修复代码
1. 修改PlayerList组件的按钮传参
两种正确写法二选一即可:
- 直接传递已经绑定好this的函数引用(无传参需求时推荐,性能更好)
<PrimaryButton onClick={this.sendConvoc}>Envoyer la convocation</PrimaryButton>
- 箭头函数内手动调用目标方法(需要传参时使用)
<PrimaryButton onClick={() => this.sendConvoc()}>Envoyer la convocation</PrimaryButton>
2. 简化/修复PrimaryButton组件
你完全不需要单独在组件类里定义onClick中转方法,直接把props传入的onClick绑定给原生button即可,同时补上type默认值:
export default class PrimaryButton extends React.Component { render () { return ( <button type={this.props.type || 'button'} onClick={this.props.onClick} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" > {this.props.children} </button> ) } }
如果一定要保留中转的onClick方法,记得绑定正确的this指向,不要套无意义的箭头函数:
export default class PrimaryButton extends React.Component { constructor(props) { super(props) this.onClick = this.onClick.bind(this) } render () { return ( <button type={this.props.type || 'button'} onClick={this.onClick} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" > {this.props.children} </button> ) } onClick() { const clickFunction = this.props.onClick if (clickFunction) { clickFunction() } } }
关键知识点
JS中函数名后紧跟括号()才代表执行函数,仅写函数名只是传递函数的引用。写箭头函数绑定事件时,如果箭头函数体内只有目标函数调用,要么直接传函数引用省掉一层多余的箭头函数,要么记得给调用的函数加括号。
内容的提问来源于stack exchange,提问作者ChillAndCode
相关产品推荐
相关产品推荐

