简体   繁体   English

按下回车键时更新输入值的问题

[英]Issue on updating Input value when enter key is pressed

I am creating, in my ReactJS-based application, a component that contains a Material Input component that allows users to type words and then display them, when the enter key is pressed, as chips in the same input component. 我正在基于ReactJS的应用程序中创建一个包含Material Input组件的组件,该组件允许用户键入单词,然后在按Enter键时将其显示为同一输入组件中的芯片。

The problem is that, after writing the first word and pressing enter, the first chip is displayed, but the updated state of the input ('') is frozen and users cannot proceed entering new words. 问题在于,在写入第一个单词并按Enter键之后,将显示第一个芯片,但是输入('')的更新状态被冻结,用户无法继续输入新单词。

If anyone know how to deal with such issue I would be extremely thankful. 如果有人知道如何处理此类问题,我将非常感谢。

import React from 'react';
import PropTypes from 'prop-types';
import Textfield from 'components/Textfield';
import Input from 'material-ui/Input';
import Chip from 'components/Chip';

class ChipInput extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      valuesEntered: [],
      inputValue: undefined,
    };
  }

  handleChange = (ev) => {
    if (ev.key === 'Enter') {
      const elements = this.state.valuesEntered;
      elements.push(<Chip label={ev.target.value} onRequestDelete={() => {}} />);
      this.setState({
        valuesEntered: elements,
        inputValue: '',
      });
    }
  }

  render = () => (
    <Input
      name='chipInput'
      onKeyPress={this.handleChange}
      value={this.state.inputValue}
      startAdornment={
        <span style={{ display: 'inline-block !important' }}>
          {
            this.state.valuesEntered
          }
        </span>
      }
    />
  );
}

export default ChipInput;

ChipInput.propTypes = {
  defaultValues: PropTypes.array,
};

You should read about Controlled Components . 您应该阅读有关受控组件的信息 In the handleChange function, you are updating state only when enter was pressed. 在handleChange函数中,仅在按下Enter键时才更新状态。 In other cases, you should update state.inputValue too with a value from an event. 在其他情况下,您也应该使用事件的值来更新state.inputValue。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM