【问题标题】:React default value does not show in input fieldReact 默认值不显示在输入字段中
【发布时间】:2019-07-13 17:29:46
【问题描述】:

我正在使用带有 React 的 Django,我正在尝试更新用户配置文件,以下是我尝试过的:

constructor(props){
    super(props);

    this.state = {
        username: '',
        fetched_data: {}
    }

async componentDidMount() {
  const token = localStorage.getItem('token');
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  config.headers["Authorization"] = `Token ${token}`;

  await axios.get(API_URL + 'users/api/user/', config)
    .then(res => {
        this.setState({fetched_data: res.data})
    })
}

onInputChange_username(event){
    this.setState({username: event.target.value});
}

<form onSubmit={this.onFormSubmit} >

    <div>
        <label>Username:</label>
        <input
            placeholder="Username"
            className="form-control"
            value={this.state.username ? this.state.username : this.state.fetched_data.username}
            onChange={this.onInputChange_username}
        />
   </div>
</form>

我首先尝试在 componentDidMount() 中获取用户数据,并将其存储在 this.state.fetched_data 中。在表单中,我尝试将值设置为 this.state.username(如果存在)。如果它是空字符串,我将其设置为 this.state.fetched_data.username。

我在上面的代码中遇到的问题是,当我尝试更改用户名中的字段时,我无法完全删除输入字段中的值。每次该字段为空时,它都会重置为 this.state.fetched_data.username 中的值。我也尝试像这样使用 defaultValue:

<div>
    <label>Username:</label>
    <input
        placeholder="Username"
        className="form-control"
        defaultValue = {this.state.fetched_data.username}
        value={this.state.username}
        onChange={this.onInputChange_username}
    />

但它也不起作用,因为它只在输入字段中显示占位符。我该如何进行这项工作?提前致谢。

【问题讨论】:

  • 您同时使用 defaultValue 和 value,删除 defaultValue 并将 this.state.username 作为初始值保持为 ' ' 并在 componentDidMount 中再次将获取数据值分配给 this.state.username ,并在onChange

标签: reactjs


【解决方案1】:

问题是您在渲染函数中对输入字段的值进行了条件赋值。当您尝试清除该字段的值时,它只会重置为 this.state.fetched_data.username,因此您永远无法清除它。

在加载表单时设置初始状态:

componentDidMount() {
    this.setState({
        username: this.state.fetched_data.username,
    });
}

然后在render中设置输入字段的值:

<input 
    value={this.state.username}
    onChange={this.onInputChange_username}
/>

而且你的 onChange 处理程序很好:

onInputChange_username(event){
    this.setState({username: event.target.value});
}

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 1970-01-01
    • 2019-01-25
    • 2023-03-06
    • 2021-02-12
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多