使用MUI构建搜索框与提交按钮,输入框无法响应按键输入
解决MUI Input组件无法记录输入的问题
你的输入框无法记录输入的核心原因是没有给MUI的Input组件绑定value属性。React中受控组件需要同时配置value和onChange,才能让输入框内容与状态双向同步。
另外补充一个规范细节:MUI的InputLabel需要通过htmlFor属性与对应的Input的id关联,确保点击标签时能聚焦到输入框。
修改后的完整代码如下:
import React from "react"; import { useState } from "react"; import { Button, InputLabel, Input, Box, FormControl } from "@mui/material"; const WeatherCitySearch = ({ city, changeCity }) => { const [tempCity, setTempCity] = useState(""); const handleTextBox = (input) => { console.log("Search Typing ... ", input.target); setTempCity(input.target.value); }; return ( <div> <h1>{city}</h1> <Box component="form"> <FormControl> {/* 添加htmlFor关联Input的id */} <InputLabel htmlFor="city-search">City</InputLabel> {/* 绑定value到tempCity状态 */} <Input type="text" id="city-search" placeholder={city} onChange={handleTextBox} value={tempCity} /> </FormControl> <Button variant="contained" onClick={() => changeCity(tempCity)}> Search </Button> </Box> </div> ); }; export default WeatherCitySearch;
修改后输入框就能正常记录输入内容,点击提交按钮也能将输入的城市值传递给父组件的changeCity函数。
内容的提问来源于stack exchange,提问作者joshmcculloch09
相关产品推荐
相关产品推荐

