javascript - 如何在 react-final-form 中将 null 作为字段的初始值传递?
问题描述
我在 a 中使用的自定义 React 组件react-final-form
<Field>
的 value 属性为int?
. 它的值可以是整数或空值。但是,当我使用组件的propnull
为该字段组件的值设置初始值时,会将 转换为空字符串。initialValues
<Form>
react-final-form
null
''
我知道我可以通过创建一个检查''
并将其转换为的包装器组件轻松解决此问题null
,但是还有其他更简洁的方法来解决这个问题吗?或者这是一个库错误?
https://codesandbox.io/s/yq00zxn271
import React from "react";
import { render } from "react-dom";
import { Form, Field } from "react-final-form";
const IntField = (props) => (
<span>
<input type="text" value={props.value === null ? 0 : props.value} />
<pre>
<b>props.{props.name} === null</b> : {(initialValues[props.name] === null).toString()}
<br />
<b>props.value === null</b> : {((isNull) => (<span style={{ color: isNull ? 'green' : 'red' }}>{isNull.toString()}</span>))(props.value === null)}
<br />
<b>props: </b>{JSON.stringify(props)}
<br />
<b>initialValues: </b>{JSON.stringify(initialValues)}
</pre>
</span>
)
const onSubmit = values => {
console.log('submitted')
}
const initialValues = { someInteger: null };
const App = () => (
<Form
initialValues={initialValues}
onSubmit={onSubmit}
render={() => (
<form>
<label>Some Integer:</label>
<Field name="someInteger">
{({ input, meta }) => (
<IntField {...input} />
)}
</Field>
</form>
)}
/>
);
render(<App />, document.getElementById("root"));
解决方案
你可以使用<Field>
道具allowNull吗?关闭此行为,以便将空值按原样传递给子组件。
像这样:
<Field name="someInteger1" allowNull={true}>
{({ input, meta }) => (
<IntField {...input} />
)}
</Field>
https://codesandbox.io/s/n4rl2j5n04
(回答我自己的问题作为对其他人的帮助,因为我花了一段时间才弄清楚发生了什么以及如何解决它)
推荐阅读
- angularjs - angularjs daterangepicker 日历显示不正确的日期
- ios - 如何使用 Core Motion 检测跳跃?
- php - RewriteRule 重定向到完整的网站 url (.htaccess)
- ios - 在快速选择/捕获后获取文件路径给出错误域=nscocoaerrordomain code=260
- python - 在 Thonny/Python 或 RaPi 中运行无限循环会锁定 IDE,如何在不重新启动的情况下摆脱它?
- google-analytics - 在 Gtag.js 上同时使用 anonymize_ip 和 optimize_id
- flutter - 格式化没有小数点的文本输入字段
- reactjs - React 传递道具
- datetime - 日期字段的 Elasticsearch 部分匹配
- ios - 无法将“Int”类型的值转换为预期的参数类型“String.Index”