我为这个组件中的输入字段创建了一个新组件,我尝试在聚焦时为输入字段提供一个类,并在焦点丢失时将其删除。 旁注表格是一个模态(npm react-responsive-modal)。一旦模态和输入组件被加载,onFocus和onBlur事件就会被触发3次。
这里是form.js组件
import React, { Component } from 'react';
class FormInput extends Component {
constructor(props) {
super(props);
this.state = {
selected: false,
};
}
onFocus = () => { // -> Gets triggered 3 Times
//this.setState({ selected: true });
console.log("Focus")
};
onBlur = () => { // -> Gets triggered 3 Times
//this.setState({ selected: false });
console.log("Leave")
};
render() {
return (
<div className="input" >
<input onFocus={this.onFocus()} onBlur={this.onBlur()} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
<label className="input-label" htmlFor={this.props.id}>E-Mail</label>
</div>
);
}
}
export default FormInput;
父组件的渲染功能。
render() {
return (
<Modal open={this.state.open} onClose={this.onCloseModal} little>
<div className="App">
{this.state.errors.map((error) => {
return <li key={error}>{error}</li>
})}
<form onSubmit={ this.onFormSubmit } autoComplete="off">
<FormInput placeholder="E-Mail" type="text" id="email"/>
<input type="submit" />
</form>
<button onClick={ this.logout }>Logout</button>
</div>
</Modal>
);
}
答案 0 :(得分:2)
当您设置onFocus
和onBlur
attribs时,您实际上是在立即调用该函数。您需要删除函数名称后的()
:
<input onFocus={this.onFocus} onBlur={this.onBlur} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
您会看到函数被调用三次,因为每次组件呈现时,它都会调用这些函数。