javascript - 如何将自定义 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
应该做什么来解决这个错误。
为可重用组件处理事件的最佳方式是什么。
非常感谢。
解决方案
我找到了解决方案。如果 prop func 没有默认值,则会给出此错误。
因此,一开始它应该包含onClick
默认值为 null。
static defaultProps = {
onClick:null
}
推荐阅读
- c++ - 返回完整的大写/小写转换字符串
- css - Bootstrap 4中li元素之间的内联管道分隔符
- c++ - 编写 C++ 程序“双倍的分数”
- visual-studio-code - 从命令行在 WSL 或 EMR 上安装 vscode 扩展
- java - Google Reflections 因扫描许多不必要的文件而减慢
- python - 向服务器 pyzmq 发送数据时出现问题
- html - 当“.top”类滚动到 150px 时,我希望“.title”类淡入淡出
- java - 对数组
在 Android 中用于过渡共享元素 - swift - Swift:在后台运行计时器并发送通知
- salt-stack - 你如何添加带有 https url 和 saltstack 的包 repo?