代码之家  ›  专栏  ›  技术社区  ›  Ralph David Abernathy

如何在React中触发onBlur事件?

  •  2
  • Ralph David Abernathy  · 技术社区  · 7 年前

    我有一个输入字段值,我想在Blur上格式化,下面是我的代码:

    组成部分 :

      <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上工作?谢谢

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ralph David Abernathy    7 年前

    多亏了这些评论,我才弄明白。我必须添加一个 onBlur 道具到 Input 像这样:

    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
  •  0
  •   Leonardo Mora    7 年前

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

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