Skip to content

Commit

Permalink
feat: support selector
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyair committed Nov 30, 2023
1 parent b4489f3 commit f031a0a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 30 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"classnames": "^2.3.2",
"dayjs": "^1.11.7",
"lodash": "^4.17.21",
"rc-field-form": "~1.27.4",
"rc-field-form": "~1.41.0",
"rc-util": "^5.30.0",
"react-is": "^18.2.0",
"runes2": "^1.1.2",
Expand Down
33 changes: 4 additions & 29 deletions src/components/form/form-subscribe.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React, { memo, useContext } from 'react'
import React, { useContext } from 'react'
import type { FC, ReactNode } from 'react'
import { FieldContext, useWatch } from 'rc-field-form'
import { useUpdate } from 'ahooks'
import type { FormInstance } from 'rc-field-form'
import type { NamePath } from 'rc-field-form/es/interface'
import { useIsomorphicUpdateLayoutEffect } from '../../utils/use-isomorphic-update-layout-effect'
import pick from 'lodash/pick'

type RenderChildren<Values = any> = (
changedValues: Record<string, any>,
Expand All @@ -18,9 +17,9 @@ export interface FormSubscribeProps {
}

export const FormSubscribe: FC<FormSubscribeProps> = props => {
const update = useUpdate()
const form = useContext(FieldContext)

useWatch(values => pick(values, props.to), form)
const value = form.getFieldsValue(props.to)

// Memo to avoid useless render
Expand All @@ -29,29 +28,5 @@ export const FormSubscribe: FC<FormSubscribeProps> = props => {
[JSON.stringify(value), props.children]
)

return (
<>
{childNode}
{props.to.map(namePath => (
<Watcher
key={namePath.toString()}
form={form}
namePath={namePath}
onChange={update}
/>
))}
</>
)
return <>{childNode}</>
}

export const Watcher = memo<{
form: FormInstance
namePath: NamePath
onChange: () => void
}>(props => {
const value = useWatch(props.namePath, props.form)
useIsomorphicUpdateLayoutEffect(() => {
props.onChange()
}, [value])
return null
})

0 comments on commit f031a0a

Please sign in to comment.