Assume that we have a reusable button component. We give an onClick
prop for the handle handleClick
event.
<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.
So at the begining it should consist of onClick
default value as null.
static defaultProps = {
onClick:null
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.