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

时间:2020-03-13 19:14:23

标签: javascript reactjs

我有2种按钮,普通的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 个答案:

答案 0 :(得分:3)

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>

答案 1 :(得分:2)

props的其余部分传递到button,它将具有onClick

    <button className={`${isGoogleSignIn? 'google-sign-in':''} custom-button`} {...buttonProps}>

答案 2 :(得分:0)

在自定义按钮元素中定义道具

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时(在孩子旁边),此方法才起作用...感谢@Taki指出这一点