简体   繁体   中英

How to fire onBlur event in React?

I have an input field value that I want to format onBlur, here is what my code looks like:

Component :

  <Input
    onBlur={this.formatEndpoint}
  />

Function :

  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');
  }

Why doesn't even the console.log() work onBlur? Thanks.

Thanks to the comments, I was able to figure it out. I had to add an onBlur prop to Input like so:

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: () => {},
};

after of a lot of search, I Did that with the follow code, in my case I am using React CS6.

class test extends React.Component {
  onBlur() {
    console.log('anything');
  }


   render () {
      let { onBlur, onChange, value, ...props } = this.props;

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM