onBlur没有被叫

时间:2017-04-04 08:51:00

标签: javascript reactjs typescript

我为输入元素制作了反应组件。

在我的应用程序中,用户可以创建一些矩形。单击矩形时,将显示属性选项卡。在这个属性选项卡中,我已经包含了几个输入组件。

当用户决定编辑f.e.矩形的名称。他点击输入改变了它,一切都完成了。

如果用户点击了我的输入组件中的下一个矩形componenWillReceiveProps

现在问题出现在onBlur事件中。

如果用户更改了名称并点击了另一个矩形,则只调用componenWillReceiveProps并忽略onBlur事件。

表示输入的值已消失,第一个矩形的名称保持不变。

输入组件(TypeScript)

export default class Input extends React.Component<InputProps, InputState> {

  static propTypes = {};

  static defaultProps = {
    type: 'text', readOnly: false, disabled: false
  };

  constructor(props: InputProps, context: any) {
    super(props, context);
    const value = props.value ? props.value : '';
    this.state = { id: props.id, value };
    this.onChange = this.onChange.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  componentWillMount() {
    const id = this.props.id || generateId();
    this.setState(assign(this.state, { id: id }));
  }

  componentWillReceiveProps(nextProps: InputProps, nextContext: any): void {
    this.setState(assign(this.state, { value: nextProps.value }));
  }

  render() {
    const id = this.state.id + '_input';
    return (
      <div className='col-xs-6'>
        <div className="input-field gd-input">
          <input id={id} type={this.props.type} value={this.state.value}
                 onChange={this.onChange}
                 placeholder={this.props.placeholder} onBlur={this.handleBlur}
                 readOnly={this.props.readOnly}
                 disabled={this.props.disabled}/>
          <label htmlFor={id}>{this.props.label}</label>
        </div>
      </div>
    );
  }

  onChange(event) {
    const value = event.target.value;
    this.setState(assign(this.state, { value }));
  }

  handleBlur(event) {
    const value = event.target.value;
    this.setState(assign(this.state, { value }));
    if (this.props.onBlur) {
      this.props.onBlur(value);
    }
  }

}

0 个答案:

没有答案
相关问题