admin管理员组

文章数量:1420929

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.

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.

Share Improve this question asked Oct 4, 2017 at 16:37 Ralph David AbernathyRalph David Abernathy 5,51813 gold badges56 silver badges87 bronze badges 3
  • 2 Looks like its a custom input. You should check if the ponent supports onBlur. – Panther Commented Oct 4, 2017 at 16:38
  • 1 Yes, what does the definition of Input look like? Did you write it? – mikkelrd Commented Oct 4, 2017 at 16:40
  • These ments helped, I just had to add an onBlur prop to Input. – Ralph David Abernathy Commented Oct 4, 2017 at 16:46
Add a ment  | 

2 Answers 2

Reset to default 2

Thanks to the ments, 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 }  />
      );
  }

}

本文标签: javascriptHow to fire onBlur event in ReactStack Overflow