reactjs - 为什么 ReactJs 表单的输入预先填充了加载值,不允许再更新它
问题描述
我使用的表单应该允许用户更新已经保存的数据的内容。后来我在表单输入中加载现有数据,如下所示: -
<input value={profile.displayName}
name="displayName" type="text"
placeholder="Display Name"
/> // it dosn't work So I tried next
<input value={profile.displayName}
name="displayName" type="text"
placeholder="Display Name"
onChange={(e) => {setDisplayName(e.target.value )}}/> // Same issue
那么如何加载现有数据并且数据必须在 from 中可编辑?
更多澄清代码:- 我正在使用这样的钩子:-
const [profile, setProfile] = useState({});
useEffect(() => {
if (props.match.params.title) {
setTitle(props.match.params.title);
} else if (props.location.state.title) {
setTitle(props.location.state.title);
}
if (props.location.state) {
if (props.location.state.profile) {
setProfile(props.location.state.profile)
console.warn("profile: ", props.location.state.profile)
}
}
}
所以配置文件来自另一个组件的道具。这部分很好。将数据加载到表单中也很好。但是加载数据后,我不能再编辑它了。
解决方案
假设你有一个像下面这样的钩子
const [displayName, setDisplayName] = useState('');
在设置配置文件的 useEffect 中还设置显示名称。
setDisplayName(props.location.state.profile.displayName)
更好地在 const 中破坏配置文件
const { profile } = props.location.state;
最后在输入中
<input value={displayName} name="displayName" type="text" placeholder="Display Name" onChange={(e) => {setDisplayName(e.target.value )}}/>
推荐阅读
- ubuntu - 除了 /mnt/ 之外,还有其他方法可以从 wsl 访问 windows 文件吗?
- windows-installer - Windows 安装程序无法执行自定义步骤
- javascript - 如何访问函数内的数组?
- javascript - 在 addEventListener() 上的 Ava 测试 setTimeout()
- python - 列表中具有固定增量的特定数字的平均值
- python - pytest:带参数的自定义标记
- php - Laravel API 返回
- java - 使用 JPA 时,将 2 个条目添加到数据库中,而不是仅添加一个
- matlab - 类“Simulink.SimulationOutput”没有合适的方法、属性或字段“时间”
- javascript - 中止在 Javascript 上管理 UX 的长异步函数