javascript - 如何解决错误,当页面中的“onChange”未在单选按钮组件中使用时
问题描述
我将此组件用于单选按钮,但是当我不使用时,有时Onchange
页面中会出现以下错误onUpdate
。
TypeError:this.props.onUpdate 不是函数
onChange(e) {
let value = e.target.value;
this.setState({value: value} );
}
render() {
return (
<div className="text-right mt-3">
{this.props.items.map(item => {
return (
<label key={item.value} className="c-radioLabel" htmlFor={item.value}>
<input
className="c-radio"
type='radio'
checked={this.state.value === item.value}
disabled={item.disabled}
value={item.value}
name={this.props.name}
onChange={this.onChange.bind(this)}
onClick={this.props.onClick} />
<span className="mr-3 ">{item.label}</span>
</label>
);
})}
</div>
解决方案
我想这与绑定有关:
onChange = value => {
//whatever you're doing with value.
}
render() {
return (
<RadioButton
required
title="Test"
onUpdate={this.onChange}
ref="test"
items={[{value: "YES", label: "yes"}, {value: "NO", label: "no"}]}
name="opt-group3"
className="radio-group"
/>
)
}
在子组件中,以这种方式更改绑定。不要.bind(this)
在渲染中使用。当调用 render() 时,将调用 this.onChange.bind(this) 来绑定处理程序。每当状态发生变化时,这将不断生成一个全新的处理程序!
onChange = (e) => {
let value = e.target.value;
this.setState({ value: value }, () => this.props.onUpdate(value));
}
render() {
return (
<div className="text-right mt-3">
{this.props.items.map(item => {
return (
<label key={item.value} className="c-radioLabel" htmlFor={item.value}>
<input
className="c-radio"
type='radio'
checked={this.state.value === item.value}
disabled={item.disabled}
value={item.value}
name={this.props.name}
onChange={event => this.onChange(event)}
onClick={this.props.onClick} />
<span className="mr-3 ">{item.label}</span>
</label>
);
})}
</div>
)
}
如果绑定处理得当,您将不会遇到this.props.onUpdate is not a function
错误。
推荐阅读
- python-3.x - Python获取对象属性
- java - 从命令提示符执行 .jar 文件时发生 JNI 错误
- django - convert_datetimefield_value() 接受 4 个位置参数,但使用 django 和 mongodb 给出了 5 个
- botframework - 无法通过 Azure 机器人服务向你的机器人添加身份验证
- javascript - 如何在 React JS 中声明全局变量
- bash - 使用 shell/bash 脚本在不同的子目录中查找公共文件
- php - Laravel Restful API,创建和存储方法
- excel - Excel查找单元格中的每个单词并与列表匹配
- amazon-dynamodb - DynamoDB 如何对表进行分区?
- css - 自定义引导菜单问题