使用 React SortableJS 和 React Hook Form 进行排序
在中文中重新排列输入表单
使用可拖拽並排序的react-sortablejs和react-hook-forms组合创建的可拖拽並排序的输入表格备忘录。
示例代码
import { ReactSortable } from 'react-sortablejs'
import { useFormContext, useFieldArray } from 'react-hook-form'
import Forms from './forms'
const sortableInputs = ()=>{
const {
control,
formState: { errors },
} = useFormContext()
const { fields, swap } = useFieldArray({
name: 'contents',
control,
})
const onEnd = (evt:any)=>{
swap(evt.oldIndex, evt.newIndex)
}
return <>
<ReactSortable list={fields} setList={()=>{}} onEnd={onEnd}>
{fields &&
fields?.map?.((field: any) => {
return (
<Forms
key={field?.id}
field={field}
/>
)
})
}
</ReactSortable>
</>
}
在ReactSortable中,使用onEnd而不是setList。在onEnd中,有oldIndex和newIndex,因此可以使用useFieldArray预先提供的swap()函数进行处理。