简体   繁体   English

如何处理自定义React事件作为组件道具

[英]How to handle Custom React Event as component prop

Assume that we have a reusable button component. 假设我们有一个可重用的按钮组件。 We give an onClick prop for the handle handleClick event. 我们为句柄handleClick事件提供onClick prop。

<Button onClick={(e)=>{doSomething(e)}}/>

But also I want to change text property of button when user click. 但是我想在用户点击时更改按钮的文本属性。

To illustrate like this: 为了说明这样:

export default class Button extends React.Component{
    static propTypes = {
       onClick:PropTypes.func
    } 

    constructor(props){
    super(props)
    this.state = {
      text:'Not Clicked the Button'
    } 
    this.handleClick = this.handleClick.bind(this) 
    }

    handleClick = (e) => {
        this.setState({text:'Clicked the Button'})
        this.props.onClick(e)
    };

    render(){
       const {text} = this.state 
       return (
            <button onClick={this.handleClick}>{text}</button>
           )
     }
}

When trying like this it is getting an error show below: 尝试这样时,会出现以下错误:

TypeError: onClick is not a function

What should be for fix this error. 应该怎么做才能解决这个错误。

What is the best way handling events for the reusable components. 处理可重用组件的事件的最佳方法是什么。

Thanks a lot. 非常感谢。

I found the solution. 我找到了解决方案。 if there is not default value of prop func it gives an this error. 如果没有prop func的默认值,则会出现此错误。

So at the begining it should consist of onClick default value as null. 所以在开始时它应该包含onClick默认值为null。

static defaultProps = {
 onClick:null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM