reactjs - 表单输入不允许在 React 表单上更改值
问题描述
我试图允许用户在表单输入中输入 ID。当他们点击提交时,它会将该表单输入值发送到 API url 以获取具有该 ID 的项目。目前,我在表单输入中看到默认值并且可以点击提交,但我无法更改输入中的值。我如何允许这样做,以便用户可以修改 ID 然后用它发送请求?然后我会用钩子处理响应
const Items: React.FC = () => {
interface Item {
id?: number;
name?: string;
}
let default = { value: "123456" };
const [item, setItem] = useState<Item>({});
const handleChange = (e: React.ChangeEvent<any>) => {
console.log(e.target.value)
};
const handleSubmit = (e: React.ChangeEvent<any>) => {
e.preventDefault();
console.log(e.target.value);
axios
.get(
`myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
)
.then((response) => setItem(response.data))
.catch((error) => console.log(error));
};
return (
<div className="toolbar-content">
<div className="row">
<form onSubmit = { handleSubmit }>
<div className="label"> MAC Address:</div>
<Input value={default.value} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
<Button className="btn" type="submit">
SUBMIT
</Button>
</form>
</div>
</div>
);
};
export default Gateways;
谢谢!
解决方案
您的 handleChange 函数应该处理这个问题。创建一个 textValue 状态并在 handleChange 函数中,将文本值设置为输入的目标值:
const Items: React.FC = () => {
interface Item {
id?: number;
name?: string;
}
let default = { value: "123456" };
const [item, setItem] = useState<Item>({});
const [textValue, setTextValue] = useState(default.value);
const handleChange = (e: React.ChangeEvent<any>) => {
setTextValue(e.target.value)
};
const handleSubmit = (e: React.ChangeEvent<any>) => {
e.preventDefault();
console.log(e.target.value);
axios
.get(
`myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
)
.then((response) => setItem(response.data))
.catch((error) => console.log(error));
};
return (
<div className="toolbar-content">
<div className="row">
<form onSubmit = { handleSubmit }>
<div className="label"> MAC Address:</div>
<Input value={textValue} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
<Button className="btn" type="submit">
SUBMIT
</Button>
</form>
</div>
</div>
);
};
export default Gateways;
推荐阅读
- imagesharp - 使用 ImageSharp 加载和保存不透明的 8 位 PNG 文件
- javascript - 无法在 Safari 上运行 webdriver.io javascript 测试
- amazon-web-services - YAML_FILE_ERROR 消息:容器标签数量错误,应为 1
- python - MYSQL CONNECTOR 加载数据本地文件:无法读取文件
- makefile - Automake 和外部条件源
- jquery - 当我使用 jquery 检查复选框时如何打开下拉列表?
- kubernetes - 使用外部域名集成外部服务时,OpenShift 中的主机名验证失败
- javascript - 反应路由器 - 没有从 url 获取参数
- c# - 列表属性实体框架的位置
- string - 字符串中的通配符作为输入