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

悠悠 2023-02-26 05:25 95阅读 0赞
  1. 如题所示,该警告出现在reactantd使用中,我们页面表单form中使用了Form.Item包含输入框,在username输入框的下面,加入了一行提示文字,代码如下:
  2. import React from 'react'
  3. import {Card,Form,Input,Button} from 'antd'
  4. import 'antd/dist/antd.css'
  5. const LoginForm = () => {
  6. const onFinish = values =>{
  7. console.log("receive values of form:",values);
  8. }
  9. const [form] = Form.useForm()
  10. return <Card>
  11. <Form name="login_form" layout={'vertical'} form={form} onFinish={onFinish}>
  12. <Form.Item label="username" name="username">
  13. <Input />
  14. <span>please input username.</span>
  15. </Form.Item>
  16. <Form.Item label="password" name="password">
  17. <Input type="password"/>
  18. </Form.Item>
  19. <Form.Item>
  20. <Button type="primary" htmlType="submit">submit</Button>
  21. </Form.Item>
  22. </Form>
  23. </Card>
  24. }
  25. export default LoginForm
  26. 效果如下:
  27. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaW5pZmk_size_16_color_FFFFFF_t_70][]
  28. 出现这个警告,最后,提交的时候,我们也会出现一个小问题,就是获取表单元素username的值,会出现undefined
  29. ![2020071414381882.gif][]
  30. 解决办法很简单,就是需要给username的这个Input输入框,加上一个Form.Item包裹起来,如下所示:
  31. <Form.Item label="username">
  32. <Form.Item name="username">
  33. <Input />
  34. </Form.Item>
  35. <span>please input username.</span>
  36. </Form.Item>
  37. 等待编译通过,页面自动刷新,警告消失,同时,我们输入相关内容,提交表单,获取表单username的值不再是undefined
  38. ![20200714144403171.gif][]
  39. 还有一种折中的解决办法,就是我们希望保留最初的这个布局,忽略警告,我们就需要在Input上增加一个onChange事件,每次输入发生改变,就通过form.setFieldsValue(\{username:e.target.value\})来为表单的username元素赋值,这个就有点复杂了,虽然最后也能在提交表单的时候获取username的值。
  40. 还有一种解决办法就是给Form.Item标签增加一个extra属性,属性的内容就是please input username.然后,Input标签后面的<span>please input username</span>这个提示内容就不需要了,删除。
  41. <Form.Item label="username" name="username" extra="please input username.">
  42. <Input />
  43. </Form.Item>
  44. 展示效果:
  45. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaW5pZmk_size_16_color_FFFFFF_t_70 1][]
  46. 提示字体颜色变为了灰色,不知道能不能更改,所以最好的解决办法就是给Input标签嵌套一个Form.Item标签。

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读