首页 > 解决方案 > 如果我想允许其他数字输入字段为空,我是否必须将输入值保存为字符串?

问题描述

I'd like to do something like:

durationScalar: number;

...

durationScalar: 1

...

this.setState({ durationScalar: valueAsNumber });

...

<input name="durationScalar" type="number" value={this.state.durationScalar} min="0"/>

但是当我清空输入字段时,我得到:

Received NaN for the `value` attribute. If this is expected, cast the value to a string.

如果我使用:

this.setState({ durationScalar: value });

然后我收到打字稿警告。

Argument of type '{ durationScalar: string; }' is not assignable to parameter of type

我可以毫无错误地执行以下操作:

durationScalar: string;

...

durationScalar: "1"

...

this.setState({ durationScalar: value });

...

<input name="durationScalar" type="number" value={this.state.durationScalar} min="0"/>

但我宁愿不必将值存储为字符串,因为它不是字符串。这里有什么好的方法?

编辑回答我如何初始化状态

interface SoftwareLicenseCodesState {
    durationScalar: number;
}

this.state = {
    durationScalar: 1
}; 

已编辑

我还想在 tsconfig 中添加它

"strictNullChecks": true,

标签: reactjstypescript

解决方案


如果你使用这个选项

 durationScalar: number | null;

或者

value={this.state.durationScalar || 0}

推荐阅读