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

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

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

    效果以下:css

     

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

     

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

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

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

    

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

    还有一种解决办法就是给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标签。 spa

相关文章
相关标签/搜索