如何在 React 中触发 onBlur 事件?
How to fire onBlur event in React?
我有一个要在 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
道具:
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: () => {},
};
经过大量搜索,我用下面的代码做到了,
就我而言,我使用的是 React CS6。
class test extends React.Component {
onBlur() {
console.log('anything');
}
render () {
let { onBlur, onChange, value, ...props } = this.props;
return (
<input onBlur={ this.onBlur } />
);
}
}
我有一个要在 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
道具:
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: () => {},
};
经过大量搜索,我用下面的代码做到了, 就我而言,我使用的是 React CS6。
class test extends React.Component {
onBlur() {
console.log('anything');
}
render () {
let { onBlur, onChange, value, ...props } = this.props;
return (
<input onBlur={ this.onBlur } />
);
}
}