有没有一种方法可以向自定义组件添加onClick事件?

5

我有两种按钮,一种是普通的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>
3个回答

14

onClick不会在您的CustomButton组件上触发,因为底层的<button>元素没有获得提供给它的onClick处理程序。您需要将buttonProps传递给自定义按钮中的底层<button>元素:

function CustomButton({className,...buttonProps}) {
    return (
        <button className={className} {...buttonProps}>
            {children}
        </button>
    )
}

{...buttonProps} 用于 <button> 元素上,它会将剩余的所有参数传递给 CustomButton 组件中的 <button> 元素。 因此,如果使用以下参数调用 CustomButton

<CustomButton className="signin" onClick={handleClick} onChange={handleChange}>
  Click me
</CustomButton>

它将有效地使按钮呈现如下:

<button className="signin" onClick={handleClick} onChange={handleChange}>
  Click me
</button>

我在不同位置使用此按钮,因此每个按钮都将有不同的事件,所以我希望在组件上添加onClick,就像我已经存在的代码一样。 - Ali El-Boghdady

4
将剩余的`props`传递给`button`,这样它就会有`onClick`。
    <button className={`${isGoogleSignIn? 'google-sign-in':''} custom-button`} {...buttonProps}>

我想知道为什么我写的这段代码不起作用,为什么普通按钮可以工作而另一个却不能。 - Ali El-Boghdady
因为CustomButton内部的那个没有onClick - Taki
啊,我明白了,你的意思是我不能在自定义组件上使用onClick,因为它将作为props传递,而不像普通按钮那样将其视为事件。 - Ali El-Boghdady
1
是的,onClick 只适用于 html 元素,例如 buttonCustomButton 不是一个 html 元素。 - Taki
我们在TypeScript中如何实现这个?Props类型是什么? - Nilupul Heshan

0

在自定义按钮元素中定义props

import React from 'react'
import  './custom-button.styles.scss'

function CustomButton({children,isGoogleSignIn,...buttonProps}) {
    return (
        <button className={`${isGoogleSignIn? 'google-sign-in':''} custom-button`} onClick={onClick}>
            {children}
        </button>
    )
}

export default CustomButton

编辑:只有在参数中解构onClick时(紧挨着children),此方法才有效... 感谢@Taki指出


1
只有在参数中解构 onClick(紧挨着 children)时,这才能正常工作。 - Taki
Troy的答案对我很有帮助。Gabriel的答案和Taki的评论让人感到困惑。如果将{...buttonProps}传递给自定义组件有效(就像Troy的答案中一样),那么在Gabriel的答案中传递onClick={onClick}的方法是什么?而且解构onClick和next到children是什么意思?代码片段是否已经根据此评论进行了修改? - Vikas Mujumdar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接