使用React的文本框中的onKeyUp事件



我有一个文本框,它接受用户输入的值。在文本框中输入值并按 Enter 键时,该值将从框中消失。因此,我正在文本框上实现onKeyUp,以便确认值。我认为我没有在正确的位置使用onKeyUp事件。用于测试的代码沙盒

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selectorValues: []
};
this.handleKeyUp = this.handleKeyUp.bind(this);
}
addSelectorValues = e => {
e.stopPropagation();
this.setState(prevState => ({
selectorValues: [...prevState.selectorValues, ""]
}));
};
removeSelectorValue(index) {
this.setState({
selectorValues: this.state.selectorValues.filter((_, i) => i !== index)
});
}
handleSelectorValueChange = index => ({ target: { value } }) => {
const selectorValues = [...this.state.selectorValues]; //makes separate copy of array.
selectorValues[index] = value;
this.setState({ selectorValues });
};
handleKeyUp(e) {
if (e.keyCode === 13) {
console.log(e.target.value);
}
}
render() {
const { selectorValues } = this.state;
return (
<div>
<form onSubmit={this.handleSubmit}>
<fieldset>
<div>
<label>Selector Values:</label>{" "}
<button
type="button"
onClick={this.addSelectorValues}
onKeyUp={this.handleKeyUp}
>
Add
</button>
{this.state.selectorValues.map((value, index) => (
<input
key={index}
type="text"
value={value}
placeholder="Enter slector values"
onChange={this.handleSelectorValueChange(index)}
required
/>
))}
<ul>
{this.state.selectorValues.map((value, index) => {
return (
<li key={index}>
{value}
<button
onClick={this.removeSelectorValue.bind(this, index)}
>
Remove
</button>
</li>
);
})}
</ul>
<br />
</div>
</fieldset>
</form>
</div>
);
}
}

你为什么不直接使用e.preventDefault()来阻止表单被提交:

handleSubmit(e) {
e.preventDefault();
// They hit enter, which submitted the form.
// Do anything you need to do here
}

在此处查看更新的代码沙盒。

最新更新