编辑 react-select 的最后输入
edit the last input of react-select
我正在使用 react-select 并且只注意到当我在输入字段中已经有值时(通过用户类型或通过选择菜单列表中的选项),然后我模糊输入然后聚焦再次尝试 - 尝试编辑我的最后一个输入 - 它只是从头开始,而不是从输入的最后一个字符继续。我刚刚在作者的github中找到了这个issue。它是从 2 年前提出的,仍然是一个悬而未决的问题。真的没有解决办法吗?
我建议您使用受控道具 inputValue
和 value
与 onChange
和 onInputChange
配对,如下面的代码:
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>
);
}
}
在 react-select v1 中,设置为 false
的 props onSelectResetsInput
正在做这项工作,但我想对于 v2 你需要做这个技巧。
这里是live example.
我正在使用 react-select 并且只注意到当我在输入字段中已经有值时(通过用户类型或通过选择菜单列表中的选项),然后我模糊输入然后聚焦再次尝试 - 尝试编辑我的最后一个输入 - 它只是从头开始,而不是从输入的最后一个字符继续。我刚刚在作者的github中找到了这个issue。它是从 2 年前提出的,仍然是一个悬而未决的问题。真的没有解决办法吗?
我建议您使用受控道具 inputValue
和 value
与 onChange
和 onInputChange
配对,如下面的代码:
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>
);
}
}
在 react-select v1 中,设置为 false
的 props onSelectResetsInput
正在做这项工作,但我想对于 v2 你需要做这个技巧。
这里是live example.