首页 > 解决方案 > 反应功能自定义按钮未注册点击

问题描述

所以这是我的功能按钮组件

export const MyButton = (props) => {
    return (
        <button className="myButton">{props.text}</button>
    )
}

我在另一个页面中使用了它

<MyButton text="Update" onClick={this.checkIt} />

该 checkIt 函数只是控制台记录我使用它的类的状态。但由于某种原因,它根本没有注册点击。我该如何解决呢?我以类似的方式实现了我使用的输入字段props.onChange(event.target.value)并且工作正常。

标签: javascriptreactjs

解决方案


您应该在子组件中附加事件,否则它根本不会绑定到实际 UI!

解决方案1:

export const MyButton = ({text, ...others}) => {
    return (
        <button className="myButton" {...others}>{text}</button>
    )
}

解决方案2:

export const MyButton = ({text, onClick}) => {
    return (
        <button className="myButton" onClick={onClick}>{text}</button>
    )
}

推荐阅读