首页 > 解决方案 > 为什么 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)
  }
}

}

所以配置文件来自另一个组件的道具。这部分很好。将数据加载到表单中也很好。但是加载数据后,我不能再编辑它了。

标签: reactjsformspreload

解决方案


假设你有一个像下面这样的钩子

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 )}}/>

推荐阅读