一、介紹laoce-react-form
1.1、背景
首先本人是一個Vue前端開發作業者,為了拓展自己的技術堆疊,這才準備揭開react的神秘面紗,當初學者react的時候,發現作為MVC框架,確實有很多不方便的地方,需要很多需要開發者自己來配置的地方,帶來了很多不便的地方,不像Vue框架,有著官方的語法糖v-model來解決雙現資料流的問題,但是react也給開發者帶來的很多自由發揮的空間,
廢話不多說了,先上github的專案地址:https://github.com/xinlong-chen865/laoce-react-form
這個專案,是react表單的雙向資料流問題的解決方案,主要思路是創建一個HOC組件,你可以把專案Demo拷貝下來,在你的專案中只引入laoce-react-form檔案夾即可,
1.2、如何引入laoce-react-form
如果你想在你的類組件中使用laoce-react-form組件,只需要引入組件,在類組件中使用裝飾器即可初始化,
import createForm from "../laoce-react-form/index";
@createForm
class Demo extends Component {
constructor(props) {
super(props);
this.state = {};
}
}
1.3、 介紹getFieldDecorator方法
在laoce-react-form的原始碼中,我是通過一個雙箭頭函式,把傳入的input組件進行一個包裝,為input組件添加一些屬性,其原理有點柯里化的感覺,如果對柯里化比較陌生的同學,可以看看這篇文章 柯里化原理,來在你的input組件上加上這個操作!
// 可以給你的表單添加一些自定義的規則
const usernameRules = { required: true, message: "請輸入username" };
const passwordRules = { required: true, message: "請輸入password" };
render() {
// 在props屬性中,就可以獲取到getFieldDecorator方法
const { getFieldDecorator } = this.props.form;
return (
<div>
<h3>MyRcForm</h3>
{getFieldDecorator("username", { rules: [usernameRules] })(
<MyInput name="姓名" />
)}
{getFieldDecorator("password", { rules: [passwordRules] })(
<MyInput name="密碼" />
)}
<button onClick={this.onSubmit}>提交</button>
</div>
);
}
1.4、介紹validateFields方法
在上面的例子中,使用getFieldDecorator方法傳入了一個rules,對input組件進行校驗,在表單收集完成后,進行表單的提交操作,可以在submit操作前,呼叫validateFields方法,例如:
// 表單提交操作
onSubmit = () => {
this.props.form.validateFields((err, state) => {
if (err) {
console.log(err);
} else {
console.log("校驗成功");
}
});
};
1.5、介紹getFieldsValue與setFieldsValue
getFieldsValue方法,他的主要功能是回應式的獲取表單的值;則setFieldsValue方法,是設定表單中的值,可用戶表單回顯功能,
componentDidMount() {
// 為表單設定值
this.props.form.setFieldsValue({ username: "chen" });
// 獲取表單的值
this.props.form.getFieldsValue();
}
二、總結
laoce-react-form組件是一個HOC模式開發的組件,通過裝飾性進行類組件的初始化,組件一共暴露出四個方法:getFieldDecorator、 setFieldsValue、 getFieldsValue、validateFields,將來會做出更多方便開發者的小開源專案,小白一枚,如有錯誤請各位大佬指點,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321274.html
標籤:其他
上一篇:你還在用古老的HTML和CSS嗎?還在手敲嗎?那么你是時候打開新前端的大門了————Element-UI全面詳解
