|
1 | | -import React from 'react'; |
2 | | -import get from 'lodash/get'; |
3 | | - |
4 | 1 | import Form, { Field } from 'rc-field-form'; |
| 2 | +import React from 'react'; |
5 | 3 | import Input from './components/Input'; |
6 | 4 |
|
7 | | -const Child = ({ name, remove }: { name: any; remove: () => void }) => { |
8 | | - const nameValue = Form.useWatch(values => { |
9 | | - return get(values, ['list', name, 'name']); |
10 | | - }); |
| 5 | +type FormData = { |
| 6 | + name?: string; |
| 7 | + password?: string; |
| 8 | + password2?: string; |
| 9 | +}; |
| 10 | + |
| 11 | +export default () => { |
| 12 | + const [form] = Form.useForm(); |
11 | 13 |
|
12 | 14 | return ( |
13 | | - <div style={{ display: 'flex' }}> |
14 | | - <Field name={[name, 'name']}> |
15 | | - <Input /> |
| 15 | + <Form |
| 16 | + form={form} |
| 17 | + preserve={false} |
| 18 | + onFieldsChange={fields => { |
| 19 | + console.error('fields:', fields); |
| 20 | + }} |
| 21 | + > |
| 22 | + <Field<FormData> name="name"> |
| 23 | + <Input placeholder="Username" /> |
| 24 | + </Field> |
| 25 | + |
| 26 | + <Field<FormData> dependencies={['name']}> |
| 27 | + {() => { |
| 28 | + return form.getFieldValue('name') === '1' ? ( |
| 29 | + <Field name="password"> |
| 30 | + <Input placeholder="Password" /> |
| 31 | + </Field> |
| 32 | + ) : null; |
| 33 | + }} |
16 | 34 | </Field> |
17 | | - <Field name={[name, 'age']}> |
18 | | - <Input /> |
| 35 | + |
| 36 | + <Field dependencies={['password']}> |
| 37 | + {() => { |
| 38 | + const password = form.getFieldValue('password'); |
| 39 | + console.log('>>>', password); |
| 40 | + return password ? ( |
| 41 | + <Field<FormData> name={['password2']}> |
| 42 | + <Input placeholder="Password 2" /> |
| 43 | + </Field> |
| 44 | + ) : null; |
| 45 | + }} |
19 | 46 | </Field> |
20 | | - <div>当前值:{nameValue}</div> |
21 | | - <button onClick={() => remove()}>删除</button> |
22 | | - </div> |
23 | | - ); |
24 | | -}; |
25 | 47 |
|
26 | | -const Demo = () => { |
27 | | - return ( |
28 | | - <Form initialValues={{ list: [{ name: 'a' }, { name: 'b' }] }}> |
29 | | - <Form.List name="list"> |
30 | | - {(fields, { remove }) => ( |
31 | | - <div style={{ display: 'flex', flexDirection: 'column' }}> |
32 | | - {fields.map(field => ( |
33 | | - <Child name={field.name} key={field.key} remove={() => remove(field.name)} /> |
34 | | - ))} |
35 | | - </div> |
36 | | - )} |
37 | | - </Form.List> |
| 48 | + <button type="submit">Submit</button> |
38 | 49 | </Form> |
39 | 50 | ); |
40 | 51 | }; |
41 | | - |
42 | | -export default Demo; |
|
0 commit comments