反应-对于某些输入,“输入”上的“值”属性不应为空”

skw*_*eth 12 reactjs

在我的React应用(版本15.5.4)中,对于其中一个组件中的输入字段,我收到以下警告:

Warning: 'value' prop on 'input' should not be null. Consider using the empty string to clear the component or 'undefined' for uncontrolled components.

引用以下jsx:

<label>Description<br />
    <input
        type="text"
        name="description"
        value={this.state.group.description}
        onChange={this.handleChange}
        maxLength="99" />
</label>
Run Code Online (Sandbox Code Playgroud)

但是我对此感到困惑,因为的值this.state.group.description""在构造函数中设置的:

this.state = {
    "group": {
        "name": "",
        "description": ""
    }
}
Run Code Online (Sandbox Code Playgroud)

更令我惊讶的是,另一个输入字段引用了this.state.group.name,但没有引发警告:

<label>Name *<br />
    <input
        type="text"
        name="name"
        value={this.state.group.name}
        onChange={this.handleChange}
        maxLength="99"
        required="required"
        autoFocus />
</label>
Run Code Online (Sandbox Code Playgroud)

我在这里想念什么吗?据我所知,我已经将这两个值的初始状态设置为空字符串,并在两个输入字段中以相同的方式引用了它们,但是一个抛出警告,一个没有警告。

这不是世界末日……该应用程序运行良好,但我真的很想了解为什么会发生这种情况并使我的应用程序正常运行。

这是handleChange

handleChange(event) {
    const attribute = event.target.name
    const updatedGroup = this.state.group
    updatedGroup[attribute] = event.target.value
    this.setState({"group": updatedGroup})
}
Run Code Online (Sandbox Code Playgroud)

Jit*_*hor 7

如果值为 null,则通过相同的错误响应 15。所以最好输入的默认道具“值”应该是一个空字符串,以便在没有警告的情况下运行 react js 代码。

<input type="text" value={value || ''}/>;
Run Code Online (Sandbox Code Playgroud)

  • 最好检查 null 以便 0 是有效值。值={值==空?““ : 价值} (2认同)
  • 谢谢。我在材质 UI 中的“Select”和“TextField”都遇到了这个问题。这意味着,“input”和“textarea”都会出现问题,因为上面的材质 UI 都是基于这两个的。 (2认同)

skw*_*eth 6

感谢@ShubhamKhatri和@Dekel为我指出了正确的方向-我什至没有考虑过构造函数中设置的空字符串被有问题的值覆盖的事实。事实证明,问题的根源在于将的值设置description为空字符串后,我的API被覆盖了null

我通过调整render方法来解决此问题,如下所示:

let groupDescription;

if (!this.state.group.description) {
    groupDescription = ""
} else {
    groupDescription = this.state.group.description
}

return (
    <label>Description<br />
        <input
            type="text"
            name="description"
            value={groupDescription}
            onChange={this.handleChange}
            maxLength="99" />
    </label>
)
Run Code Online (Sandbox Code Playgroud)

  • 因此,您可以选择,另一种解决方案是使用二进制运算符。例如`&lt;输入值= {groupDescription || “”}`。 (6认同)
  • 读者请注意使用“||”*而不是*“|”,这几乎肯定会产生意外的行为。诚挚的:我的最后 15 分钟 (5认同)

Shu*_*tri 5

问题出在handleChange函数上,您直接在改变状态

const updatedGroup = this.state.group
updatedGroup[attribute] = event.target.value 
Run Code Online (Sandbox Code Playgroud)

用于spread operator克隆组对象

handleChange(event) {
    const attribute = event.target.name
    const updatedGroup = [...this.state.group]
    updatedGroup[attribute] = event.target.value
    this.setState({"group": updatedGroup})
}
Run Code Online (Sandbox Code Playgroud)