reactjs - 如果我想允许其他数字输入字段为空,我是否必须将输入值保存为字符串?
问题描述
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,
解决方案
如果你使用这个选项
durationScalar: number | null;
或者
value={this.state.durationScalar || 0}
推荐阅读
- c# - 从 Google Api 读取电子邮件后如何设置状态
- pandas - 将数据框中的日期时间转换为秒
- php - 如何将参数从客户端传递到 PHP
- maple - 是否有从所有输出中清除工作表的命令?(不使用图形用户界面)
- php - Nginx 使用端口 80 和 8080
- distributed-computing - 中心化VS去中心化?单点故障?
- javascript - GET 和 POST 方法以及如何使用它们
- mysql - 从表格的特定字段中删除字符
- javascript - 强制页面在重新加载时返回顶部 - Javascript
- ruby-on-rails - Rails 5 为文章和评论添加点赞