首页 > 解决方案 > 如何将自定义 React 事件作为组件道具处理

问题描述

假设我们有一个可重用的按钮组件。我们为句柄事件提供一个onClick道具。handleClick

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

但我也想在用户单击时更改按钮的文本属性。

像这样说明:

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>
           )
     }
}

像这样尝试时,会出现以下错误:

TypeError: onClick is not a function

应该做什么来解决这个错误。

为可重用组件处理事件的最佳方式是什么。

非常感谢。

标签: javascriptreactjs

解决方案


我找到了解决方案。如果 prop func 没有默认值,则会给出此错误。

因此,一开始它应该包含onClick默认值为 null。

static defaultProps = {
 onClick:null
}

推荐阅读