可以通过为输入框绑定"onKeyPress"事件并在事件处理程序中检查按键是否为回车来解决此问题。如果是回车键,则设置状态值并调用提交函数。
示例代码:
import React, { useState } from 'react';
function Test() {
const [inputValue, setInputValue] = useState('');
const handleSubmit = () => {
console.log('Submitted: ' + inputValue);
}
const handleKeyPress = (event) => {
if (event.key === 'Enter') {
setInputValue(event.target.value);
handleSubmit();
}
}
return (
);
}
export default Test;