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

相關文章
相關標籤/搜索