Как очистить состояние в реакции на `onKeyDown` в форме ввода? - PullRequest
0 голосов
/ 15 ноября 2018

У меня есть компонент ввода в React, где ввод отправляется нажатием клавиши Enter. Я использую material-ui компоненты в качестве основы для моего компонента. Внутри onKeyDown четного обработчика я очищаю состояние, назначая пустую строку единственному полю в состоянии компонента. Однако это не работает. Что я делаю не так?

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '@material-ui/core/InputBase';
import { withStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { getAppInfo } from '../../actions/appActions.js';

const styles = theme => ({
  inputRoot: {
    color: 'inherit',
    width: '100%',
  }
})

class AppSearchBarInput extends Component {
  state = {
    appId: ''
  }

  onChange = e => {
    this.setState({ appId: e.target.value });
  }

  onKeyDown = e => {

    const { appId } = this.state;

    if (e.keyCode === 13) {
      this.props.getAppInfo({ appId });
      this.setState({
        appId: ''
      });
      this.props.history.push('/');
    }
  }

  render() {
    const { classes } = this.props;

    return (
      <InputBase
        placeholder="Search…"
        classes={{
          root: classes.inputRoot,
          input: classes.inputInput,
        }}
        onChange={this.onChange}
        onKeyDown={this.onKeyDown}
      />
    )
  }
}

const AppSearchBarWithStyles = withStyles(styles)(AppSearchBarInput);
const AppSearchBarWithStylesWithRouter = withRouter(AppSearchBarWithStyles);
export default connect(null, { getAppInfo })(AppSearchBarWithStylesWithRouter);

1 Ответ

0 голосов
/ 15 ноября 2018

Вам нужно установить значение Input, иначе он не знает, какую переменную отображать, и использует свою собственную, которая не очищается.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '@material-ui/core/InputBase';
import { withStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { getAppInfo } from '../../actions/appActions.js';

const styles = theme => ({
  inputRoot: {
    color: 'inherit',
    width: '100%',
  }
})

class AppSearchBarInput extends Component {
  state = {
    appId: ''
  }

  onChange = e => {
    this.setState({ appId: e.target.value });
  }

  onKeyDown = e => {

    const { appId } = this.state;

    if (e.keyCode === 13) {
      this.props.getAppInfo({ appId });
      this.setState({
        appId: ''
      });
      this.props.history.push('/');
    }
  }

  render() {
    const { classes } = this.props;

    return (
      <InputBase
        placeholder="Search…"
        classes={{
          root: classes.inputRoot,
          input: classes.inputInput,
        }}
        onChange={this.onChange}
        onKeyDown={this.onKeyDown}
        value={this.state.appId}
      />
    )
  }
}

const AppSearchBarWithStyles = withStyles(styles)(AppSearchBarInput);
const AppSearchBarWithStylesWithRouter = withRouter(AppSearchBarWithStyles);
export default connect(null, { getAppInfo })(AppSearchBarWithStylesWithRouter);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...