簡體   English   中英

如何處理自定義React事件作為組件道具

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

假設我們有一個可重用的按鈕組件。 我們為句柄handleClick事件提供onClick prop。

<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

應該怎么做才能解決這個錯誤。

處理可重用組件的事件的最佳方法是什么。

非常感謝。

我找到了解決方案。 如果沒有prop func的默認值,則會出現此錯誤。

所以在開始時它應該包含onClick默認值為null。

static defaultProps = {
 onClick:null
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM