首页 文章

OnFocus和onBlur在没有聚焦或离开输入字段的情况下被激活3次

提问于
浏览
0

我为这个组件中的输入字段创建了一个新组件,我尝试在聚焦时为输入字段提供一个类,并在焦点丢失时将其删除 . 旁注表格是一个模态(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>
    );
}

1 回答

  • 1

    当您设置 onFocusonBlur 属性时,您实际上是立即调用该函数 . 您需要在函数名称后删除 ()

    <input onFocus={this.onFocus} onBlur={this.onBlur} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
    

    您会看到函数被调用三次,因为每次组件呈现时,它都会调用这些函数 .

相关问题