在 React 中使用表單有個明顯的痛點,就是須要維護大量的value
和onChange
,好比一個簡單的登陸框:javascript
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: ""
};
}
onUsernameChange = e => {
this.setState({ username: e.target.value });
};
onPasswordChange = e => {
this.setState({ password: e.target.value });
};
onSubmit = () => {
const data = this.state;
// ...
};
render() {
const { username, password } = this.state;
return (
<form onSubmit={this.onSubmit}>
<input value={username} onChange={this.onUsernameChange} />
<input
type="password"
value={password}
onChange={this.onPasswordChange}
/>
<button>Submit</button>
</form>
);
}
}
複製代碼
這已是比較簡單的登陸頁,一些涉及到詳情編輯的頁面,十多二十個組件也是常有的。一旦組件多起來就會有許多弊端:java
setState
的使用,會致使從新渲染,若是子組件沒有相關優化,至關影響性能。總結起來,做爲一個開發者,迫切但願能有一個表單組件可以同時擁有這樣的特性:react
表單組件社區上已經有很多方案,例如react-final-form、formik,ant-plus、noform等,許多組件庫也提供了不一樣方式的支持,如ant-design。git
但這些方案都或多或少一些重量,又或者使用方法仍然不夠簡便,天然造輪子纔是最能複合要求的選擇。github
這個表單組件實現起來主要分爲三部分:npm
Form
:用於傳遞表單上下文。Field
: 表單域組件,用於自動傳入value
和onChange
到表單組件。FormStore
: 存儲表單數據,封裝相關操做。爲了能減小使用ref
,同時又能操做表單數據(取值、修改值、手動校驗等),我將用於存儲數據的FormStore
,從Form
組件中分離出來,經過new FormStore()
建立並手動傳入Form
組件。數組
使用方式大概會長這樣子:併發
class App extends React.Component {
constructor(props) {
super(props);
this.store = new FormStore();
}
onSubmit = () => {
const data = this.store.get();
// ...
};
render() {
return (
<Form store={this.store} onSubmit={this.onSubmit}> <Field name="username"> <input /> </Field> <Field name="password"> <input type="password" /> </Field> <button>Submit</button> </Form> ); } } 複製代碼
用於存放表單數據、接受表單初始值,以及封裝對錶單數據的操做。ide
class FormStore {
constructor(defaultValues = {}, rules = {}) {
// 表單值
this.values = defaultValues;
// 表單初始值,用於重置表單
this.defaultValues = deepCopy(defaultValues);
// 表單校驗規則
this.rules = rules;
// 事件回調
this.listeners = [];
}
}
複製代碼
爲了讓表單數據變更時,可以響應到對應的表單域組件,這裏使用了訂閱方式,在FormStore
中維護一個事件回調列表listeners
,每一個Field
建立時,經過調用FormStore.subscribe(listener)
訂閱表單數據變更。函數
class FormStore {
// constructor ...
subscribe(listener) {
this.listeners.push(listener);
// 返回一個用於取消訂閱的函數
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) this.listeners.splice(index, 1);
};
}
// 通知表單變更,調用全部listener
notify(name) {
this.listeners.forEach(listener => listener(name));
}
}
複製代碼
再添加get
和set
函數,用於獲取和設置表單數據。其中,在set
函數中調用notify(name)
,以保證全部的表單變更都會觸發通知。
class FormStore {
// constructor ...
// subscribe ...
// notify ...
// 獲取表單值
get(name) {
// 若是傳入name,返回對應的表單值,不然返回整個表單的值
return name === undefined ? this.values : this.values[name];
}
// 設置表單值
set(name, value) {
//若是指定了name
if (typeof name === "string") {
// 設置name對應的值
this.values[name] = value;
// 執行表單校驗,見下
this.validate(name);
// 通知表單變更
this.notify(name);
}
// 批量設置表單值
else if (name) {
const values = name;
Object.keys(values).forEach(key => this.set(key, values[key]));
}
}
// 重置表單值
reset() {
// 清空錯誤信息
this.errors = {};
// 重置默認值
this.values = deepCopy(this.defaultValues);
// 執行通知
this.notify("*");
}
}
複製代碼
對於表單校驗部分,不想考慮得太複雜,只作一些規定
FormStore
構造函數中傳入的rules
是一個對象,該對象的鍵對應於表單域的name
,值是一個校驗函數
。校驗函數
參數接受表單域的值和整個表單值,返回boolean
或string
類型的結果。true
表明校驗經過。false
和string
表明校驗失敗,而且string
結果表明錯誤信息。而後巧妙地經過||
符號判斷是否校驗經過,例如:
new FormStore({/* 初始值 */, {
username: (val) => !!val.trim() || '用戶名不能爲空',
password: (val) => !!(val.length > 6 && val.length < 18) || '密碼長度必須大於6個字符,小於18個字符',
passwordAgain: (val, vals) => val === vals.password || '兩次輸入密碼不一致'
}})
複製代碼
在FormStore
實現一個validate
函數:
class FormStore {
// constructor ...
// subscribe ...
// notify ...
// get
// set
// reset
// 用於設置和獲取錯誤信息
error(name, value) {
const args = arguments;
// 若是沒有傳入參數,則返回錯誤信息中的第一條
// const errors = store.error()
if (args.length === 0) return this.errors;
// 若是傳入的name是number類型,返回第i條錯誤信息
// const error = store.error(0)
if (typeof name === "number") {
name = Object.keys(this.errors)[name];
}
// 若是傳了value,則根據value值設置或刪除name對應的錯誤信息
if (args.length === 2) {
if (value === undefined) {
delete this.error[name];
} else {
this.errors[name] = value;
}
}
// 返回錯誤信息
return this.errors[name];
}
// 用於表單校驗
validate(name) {
if (name === undefined) {
// 遍歷校驗整個表單
Object.keys(this.rules).forEach(n => this.validate(n));
// 並通知整個表單的變更
this.notify("*");
// 返回一個包含第一條錯誤信息和表單值的數組
return [this.error(0), this.get()];
}
// 根據name獲取校驗函數
const validator = this.rules[name];
// 根據name獲取表單值
const value = this.get(name);
// 執行校驗函數獲得結果
const result = validator ? validator(name, this.values) : true;
// 獲取並設置結果中的錯誤信息
const message = this.error(
name,
result === true ? undefined : result || ""
);
// 返回Error對象或undefind,和表單值
const error = message === undefined ? undefined : new Error(message);
return [error, value];
}
}
複製代碼
至此,這個表單組件的核心部分FormStore
已經完成了,接下來就是這麼在Form
和Field
組件中使用它。
Form
組件至關簡單,也只是爲了提供一個入口和傳遞上下文。
props
接收一個FormStore
的實例,並經過Context
傳遞給子組件(即Field
)中。
const FormStoreContext = React.createContext();
function Form(props) {
const { store, children, onSubmit } = props;
return (
<FormStoreContext.Provider value={store}> <form onSubmit={onSubmit}>{children}</form> </FormStoreContext.Provider> ); } 複製代碼
Field
組件也並不複雜,核心目標是實現value
和onChange
自動傳入到表單組件中。
// 從onChange事件中獲取表單值,這裏主要應對checkbox的特殊狀況
function getValueFromEvent(e) {
return e && e.target
? e.target.type === "checkbox"
? e.target.checked
: e.target.value
: e;
}
function Field(props) {
const { label, name, children } = props;
// 拿到Form傳下來的FormStore實例
const store = React.useContext(FormStoreContext);
// 組件內部狀態,用於觸發組件的從新渲染
const [value, setValue] = React.useState(
name && store ? store.get(name) : undefined
);
const [error, setError] = React.useState(undefined);
// 表單組件onChange事件,用於從事件中取得表單值
const onChange = React.useCallback(
(...args) => name && store && store.set(name, valueGetter(...args)),
[name, store]
);
// 訂閱表單數據變更
React.useEffect(() => {
if (!name || !store) return;
return store.subscribe(n => {
// 當前name的數據發生了變更,獲取數據並從新渲染
if (n === name || n === "*") {
setValue(store.get(name));
setError(store.error(name));
}
});
}, [name, store]);
let child = children;
// 若是children是一個合法的組件,傳入value和onChange
if (name && store && React.isValidElement(child)) {
const childProps = { value, onChange };
child = React.cloneElement(child, childProps);
}
// 表單結構,具體的樣式就不貼出來了
return (
<div className="form"> <label className="form__label">{label}</label> <div className="form__content"> <div className="form__control">{child}</div> <div className="form__message">{error}</div> </div> </div>
);
}
複製代碼
因而,這個表單組件就完成了,愉快地使用它吧:
class App extends React.Component {
constructor(props) {
super(props);
this.store = new FormStore();
}
onSubmit = () => {
const data = this.store.get();
// ...
};
render() {
return (
<Form store={this.store} onSubmit={this.onSubmit}> <Field name="username"> <input /> </Field> <Field name="password"> <input type="password" /> </Field> <button>Submit</button> </Form> ); } } 複製代碼
這裏只是把最核心的代碼整理了出來,功能上固然比不上那些成百上千 star 的組件,可是用法上足夠簡單,而且已經能應對項目中的大多數狀況。
我已在此基礎上完善了一些細節,併發布了一個 npm 包——@react-hero/form
,你能夠經過npm安裝,或者在github上找到源碼。若是你有任何已經或建議,歡迎在評論或 issue 中討論。