React Native使用Formik表单报错:React.Children.only仅接受单个子元素
报错原因及解决方法:Error: React.Children.only expected to receive a single React element child(Formik + React Native)
报错核心原因
Formik组件内部通过React.Children.only做校验,要求直接子元素必须是单个React元素,不允许存在多个同级直接子节点,也不能夹杂文本、换行空格、单行注释这类会被React解析为文本节点的内容。即便移除了TextInput外层的View,只要Formik的直接子元素是多个,或者存在隐性文本节点,就会触发该错误。
具体解决方法
用单个容器包裹所有子元素
将Formik下的所有表单元素、按钮、提示文本等,统一放在一个View(React Native中推荐使用View,也可用React.Fragment)内,示例代码:<Formik initialValues={{ email: '', password: '' }} onSubmit={(values) => console.log('提交的值:', values)} > <View style={{ padding: 16 }}> <TextInput placeholder="邮箱" onChangeText={(text) => props.setFieldValue('email', text)} value={props.values.email} /> <TextInput placeholder="密码" secureTextEntry onChangeText={(text) => props.setFieldValue('password', text)} value={props.values.password} /> <Button title="提交表单" onPress={props.handleSubmit} /> </View> </Formik>清理隐性文本节点
注意Formik标签内的换行、空格、单行注释(//开头的注释若放在子元素位置,会被React识别为文本节点),比如以下写法会触发错误:<Formik ...> // 邮箱输入框 <TextInput ... /> <TextInput ... /> </Formik>需将这类注释移到Formik标签外,或用容器包裹子元素,避免出现多节点。
检查render props模式的返回值
若使用Formik的render prop写法,确保render函数返回单个元素,不能直接返回多个同级节点:<Formik initialValues={{ email: '' }} onSubmit={(values) => console.log(values)} > {(props) => ( // 必须用单个容器包裹返回内容 <View> <TextInput placeholder="邮箱" onChangeText={(text) => props.setFieldValue('email', text)} value={props.values.email} /> <Button title="提交" onPress={props.handleSubmit} /> </View> )} </Formik>
内容的提问来源于stack exchange,提问作者Harsh Mishra
相关产品推荐
相关产品推荐

