edit the last input of react-select

那年仲夏 提交于 2019-12-13 08:41:58

问题


I am using react-select and just notice that when I already have value in the input field (either by user type or by choosing the option in menu list), then I blur the input then focus at it again - trying to edit my last input - its just start over from the beginning, not continue from the last character of the input. I just found this issue in the author's github. Its been raised from 2 years ago and still an open issue. Is there really no workaround to achieve this?


回答1:


I recommend you to use controlled props inputValue and value pair with onChange and onInputChange like the following code:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      inputValue: "",
      value: ""
    };
  }
  onInputChange = (option, { action }) => {
    console.log(option, action);
    if (action === "input-change") {
      const optionLength = option.length;
      const inputValue = this.state.inputValue;
      const inputValueLength = inputValue.length;

      const newInputValue =
        optionLength < inputValueLength
          ? option
          : this.state.inputValue + option[option.length - 1];
      this.setState({
        inputValue: newInputValue
      });
    }
  };
  onChange = option => {
    this.setState({
      value: option
    });
  };
  render() {
    return (
      <div className="App">
        <Select
          options={options}
          onChange={this.onChange}
          onInputChange={this.onInputChange}
          inputValue={this.state.inputValue}
          value={this.state.value}
        />
      </div>
    );
  }
}

In react-select v1 the props onSelectResetsInput set to false was doing this job but I guess for v2 you will need to do the trick.

Here a live example.



来源:https://stackoverflow.com/questions/54819925/edit-the-last-input-of-react-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!