antd Form、Filed的使用
function MyRCFieldDorm(props){
const [form]=Form.useForm();
useEffect(()=>{
form.setFieldValue({username:"default"})
},[])
return(
<Form form={form}>
<Field name="username">
<Input placeholder="input"/>
</Field>
</form>
)
}
实现Form Field
index.js
import _Form from './Form'
import Field from './Field'
import useForm from './useForm'
const Form=_Form
Form.useFoem=useForm
export {Field}
export default Form
Form.js
import React from "react";
import FieldContext from './FieldContext'
import useForm from './useForm'
export default function(form,children,onFinish,onFinishFailed){
const [formInstance]=useForm();
formInstance.setCallback({
onFinish,
onFinishFailed
})
return <form
onSubmit={(event)=>{
event.preventDefault()
}}>
<FieldContext.Provider value={formInstance}>
{children}
</FieldContext.Provider>
</form>
}
Field.js
import React from 'react';
import FieldContext from './FieldContext'
export default class Field extends Component{
static contextType=FieldContext;
componentDidMount(){
const {registerEntity}=this.context;
registerEntity(this)
}
onStoreChange=()=>{
this.forceUpdate();
}
getControlled=()=>{
const {name}=this.props;
const {setFieldsValue,getFieldValue}=this.context;
return{
value:getFieldValue(name),
onChange:event=>{
const newValue=event.target.value;
setFieldValue({
[name]:newValue
})
}
}
}
render(){
const {childrren}=this.props;
const returnChildNode=React.cloneElement(children,this.getControlled)
return returnChildNode
}
}
useForm.js
import React,{useRef} from 'react'
class FormStore{
constructor(){
this.store={}
this.fieldEnetities=[]
this.callback={}
}
registerEntity=(entity)=>{
this.fieldEnetities.push(entity)
return ()=>{
this.fieldEnetities=this.fieldEnetities.filter(item=>item!==entity);
delete this.store[entity.props.name]
}
}
setCallback=(callback)=>{
this.callback={
...this.callback,
...callback
}
}
submit=()=>{
console.log('提交')
}
setFieldValue=()=>{}
setFieldsValue=(newStroe)=>{
this.store={
...this.store,
...newStore
}
this.fieldEnetities.forEach(entity=>{
const {name}=entity.props;
Object.keys(newStore).forEach(key=>{
if(key===name){
entity.onStoreChange();
}
})
})
}
getFiledValue=(name)=>{
return this.store[name]
}
getForm(){
return{
setFieldValue:this.setFieldValue,
setFieldsValue:this.setFieldsValue,
getFiledValue:this.getFiledValue
submit:this.submit,
setCallback:this.setCallback
}
}
}
export default fucntion useForm(form){
const formRef=useRef();
if(!formRef.current){
if(!form){
formRef.current=form
}else{
const formStore=new FormStore();
formRef.current=formStore.current;
}
}
return [formRef.current]
}
FileContext.js
import React from "react"
const FieldContext=React.createContext();
export default FieldContext;