【问题标题】:How to fire onBlur event in React?如何在 React 中触发 onBlur 事件?
【发布时间】:2018-01-09 06:21:27
【问题描述】:

我有一个要格式化 onBlur 的输入字段值,我的代码如下所示:

组件

  <Input
    onBlur={this.formatEndpoint}
  />

功能

  formatEndpoint() {
    let endpoint = this.state.inputEndpoint;

    endpoint = endpoint.replace(/\s/g, '').replace(/\/+$/, '');

    if (endpoint.slice(-1) === '/') {
      endpoint = endpoint.substring(0, endpoint.length - 1);
    }

    console.log('anything');
  }

为什么连console.log() 都不能在Blur 上工作?谢谢。

【问题讨论】:

  • 看起来像是自定义的input。你应该检查组件是否支持onBlur
  • 是的,Input 的定义是什么样的?你写的吗?
  • 这些 cmets 有帮助,我只需要添加一个 onBlur 属性到 Input

标签: javascript function reactjs onblur


【解决方案1】:

感谢 cmets,我能够弄清楚。我必须像这样向Input 添加一个onBlur 道具:

export default class Input extends React.Component {
  constructor() {
    super();
    this.handleBlur = this.handleBlur.bind(this);
  }

  handleBlur() {
    const { onBlur } = this.props;
    onBlur();
  }

  render() {
    return <input onBlur={this.handleBlur} />
  }
}

Input.propTypes = {
  onBlur: PropTypes.func,
};

Input.defaultProps = {
  onBlur: () => {},
};

【讨论】:

    【解决方案2】:

    经过大量搜索后,我使用以下代码做到了, 就我而言,我使用的是 React CS6。

    class test extends React.Component {
      onBlur() {
        console.log('anything');
      }
    
    
       render () {
          let { onBlur, onChange, value, ...props } = this.props;
    
          return (
            <input onBlur={ this.onBlur }  />
          );
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2017-10-23
      • 2022-10-30
      • 2011-09-26
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多