Как обработать 'Enter' на вводе в React - PullRequest
0 голосов
/ 30 апреля 2018

У меня есть форма в React, с кнопкой ввода и поиска. В настоящее время кнопка поиска выполняет поиск. Я хочу, если пользователь нажимает Enter в поле, кнопка поиска срабатывает.

В настоящее время Enter просто очищает поле ввода. У меня есть onClickhandler на кнопку поиска. Я хочу применить тот же обработчик к событию Keydown или Keypress для Field.

Ниже мой код:

import React, {Component} from 'react';
import {FormattedMessage} from 'react-intl';
import {FormField, Form} from 'digitalexp-common-components-l9';
import Input from 'digitalexp-common-components-l9/lib/form-field/Input';
import messages from 'digitalexp-select-additional-charges-retail-module-l9/src/widget/SelectAdditionalCharges.i18n';

const {FormContainer} = Form;

@FormContainer({hasDefaults: true})
export default class SelectAdditionalChargesSearchBoxView extends Component {
    constructor(props) {
        super(props);
        this.handleSearchClick = this.handleSearchClick.bind(this);
        this.handleClearClick = this.handleClearClick.bind(this);
    }

    componentWillMount() {
        this.props.initializeFormValues({searchkey: this.props.searchBy});
    }

    handleClearClick() {
        const {updateField} = this.props;
        updateField({name: 'searchkey', value: ''}).then(() => this.props.handleSearchBy({searchkey: ''}));
    }

    handleSearchClick(e) {
        const {handleSubmit, handleSearchBy} = this.props;
        e.preventDefault();
        handleSubmit(handleSearchBy);
    }

    render() {
        const {Field} = FormField;
        return (
            <div className="ds-search-panel">
                <div className="ds-search-panel__header">
                    <FormattedMessage {...messages.SelectSearchAdditionalCharges} />
                </div>
                <form
                    className="ds-search-panel__footer"
                    autoComplete="off"
                    onSubmit={this.handleSearchClick}>
                    <span className="ds-search-panel__footer--names">
                        <FormattedMessage {...messages.nameLabel} />
                    </span>
                    <span className="ds-search-panel__footer--textfields">
                        <Field
                            Component={Input}
                            name="searchkey"
                            autoComplete="off"
                            config={{rowLabel: true}}
                        />
                    </span>
                    <span className="ds-search-panel__footer--search">
                        <button className="ds-btn ds-btn--secondary ds-btn--searches" onClick={this.handleClearClick}>
                            <span className="ds-btn--span">
                                <FormattedMessage {...messages.clearButtonText} />
                            </span>
                        </button>
                        <button className="ds-btn ds-btn--primary ds-btn--searches" onClick={this.handleSearchClick}>
                            <span className="ds-btn--span">
                                <FormattedMessage {...messages.searchButtonText} />
                            </span>
                        </button>
                    </span>
                </form>
            </div>
        );
    }
}

И ниже класс Input.js:

import React from 'react';
import classNames from 'classnames';

const Input = (props) => {
    const {
        input, label, type = 'text', usePlaceholder, meta: {error}, displayInlineError = true,
        fieldIconClassName, showCloseButton, fieldIconEventListener, clearField
    } = props;
    let {fieldClassName = 'ds-text'} = props;
    const {name, placeholder} = input;

    fieldClassName = classNames('ds-form__input', {
        [fieldClassName]: fieldClassName
    });

    let fieldIconProps = {
        className: classNames({
            'ds-form__icon': true,
            [fieldIconClassName]: fieldIconClassName
        })
    };

    if (fieldIconEventListener) {
        fieldIconProps = {
            ...fieldIconProps,
            onClick: fieldIconEventListener
        };
    }

    return (
        <div className="ds-form__input--wrapper">
            <input
                id={name}
                {...input}
                placeholder={usePlaceholder ? placeholder || label : ''}
                type={type}
                className={fieldClassName}
            />
            {showCloseButton && <button className="ds-form__icon ds-form__icon--close" onMouseDown={clearField} />}
            {fieldIconClassName && <div {...fieldIconProps} />}
            {(error && displayInlineError) && <div className="ds-notification__error--text">{error}</div>}
        </div>
    );
};

export default Input;

Может ли кто-нибудь помочь?

1 Ответ

0 голосов
/ 30 апреля 2018

Вы можете просто прикрепить обработчик onKeyDown или onKeyUp к Field

handleKeyPress (e) {
     // This is perfectly safe in react, it correctly detect the keys
     if(event.key == 'Enter'){
        this.handleSearchClick(e)
      }
    }

<Field onKeyDown={this.handleKeyPress}
...