react+antd form 警告Warning: [antd: Form.Item] `children` is array of render props cannot have `name`.

2023-05-16

    如题所示,该警告出现在react与antd使用中,我们页面表单form中使用了Form.Item包含输入框,在username输入框的下面,加入了一行提示文字,代码如下:

import React from 'react'
import {Card,Form,Input,Button} from 'antd'
import 'antd/dist/antd.css'
const LoginForm = () => {
	const onFinish = values =>{	
		console.log("receive values of form:",values);
	}
	const [form] = Form.useForm()
	return <Card>
	  <Form name="login_form" layout={'vertical'} form={form} onFinish={onFinish}>
		<Form.Item label="username" name="username">
			<Input />
			<span>please input username.</span>
		</Form.Item>
		<Form.Item label="password" name="password">
			<Input type="password"/>
		</Form.Item>
		<Form.Item>
			<Button type="primary" htmlType="submit">submit</Button>
		</Form.Item>
	  </Form>
	</Card>
}

export default LoginForm

    效果如下:

     

    出现这个警告,最后,提交的时候,我们也会出现一个小问题,就是获取表单元素username的值,会出现undefined。

     

     解决办法很简单,就是需要给username的这个Input输入框,加上一个Form.Item包裹起来,如下所示:

<Form.Item label="username">
	<Form.Item name="username">
		<Input />
	</Form.Item>
	<span>please input username.</span>
</Form.Item>

    等待编译通过,页面自动刷新,警告消失,同时,我们输入相关内容,提交表单,获取表单username的值不再是undefined。

    

    还有一种折中的解决办法,就是我们希望保留最初的这个布局,忽略警告,我们就需要在Input上增加一个onChange事件,每次输入发生改变,就通过form.setFieldsValue({username:e.target.value})来为表单的username元素赋值,这个就有点复杂了,虽然最后也能在提交表单的时候获取username的值。

    还有一种解决办法就是给Form.Item标签增加一个extra属性,属性的内容就是please input username.然后,Input标签后面的<span>please input username</span>这个提示内容就不需要了,删除。

<Form.Item label="username" name="username" extra="please input username.">
	<Input />
</Form.Item>

     展示效果:

    

    提示字体颜色变为了灰色,不知道能不能更改,所以最好的解决办法就是给Input标签嵌套一个Form.Item标签。 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react+antd form 警告Warning: [antd: Form.Item] `children` is array of render props cannot have `name`. 的相关文章

随机推荐