首页 > 解决方案 > 如何解决错误,当页面中的“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>

标签: javascriptreactjsradio-button

解决方案


我想这与绑定有关:

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错误。


推荐阅读