我有两种按钮,一个普通的 html 按钮和另一个自定义按钮。我只能在普通按钮上使用 onClick 但另一个不起作用。
我拥有的自定义按钮:
import React from 'react'
import './custom-button.styles.scss'
function CustomButton({children,isGoogleSignIn,...buttonProps}) {
return (
<button className={`${isGoogleSignIn? 'google-sign-in':''} custom-button`}>
{children}
</button>
)
}
export default CustomButton
我使用它的代码:<button onClick={() => alert("Normal button")}>Click me</button>
<CustomButton onClick={() => alert("Custom button")}>Click me</CustomButton>
最佳答案
onClick
没有在你的 CustomButton
上开火组件因为底层<button>
元素没有得到 onClick
提供给它的处理程序。您需要通过 buttonProps
到基础<button>
自定义按钮中的元素:
function CustomButton({className,...buttonProps}) {
return (
<button className={className} {...buttonProps}>
{children}
</button>
)
}
{...buttonProps}
的使用在 <button>
element 基本上将所有剩余的 props 传递给 CustomButton
<button>
的组件元素。因此,如果您调用 CustomButton
使用这些 Prop :<CustomButton className="signin" onClick={handleClick} onChange={handleChange}>
Click me
</CustomButton>
它会像这样有效地呈现按钮:
<button className="signin" onClick={handleClick} onChange={handleChange}>
Click me
</button>
关于javascript - 有没有办法将 onClick 事件添加到自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676075/