68 lines
2.5 KiB
React
68 lines
2.5 KiB
React
import React, { useState, useEffect } from 'react';
|
||
import './FormModal.css';
|
||
|
||
const DEFAULT_FIELDS = [
|
||
{ key: 'name', label: '姓名', required: true, placeholder: '请输入姓名' },
|
||
{ key: 'email', label: '邮箱', required: true, placeholder: 'name@example.com' },
|
||
{ key: 'role', label: '角色', placeholder: '如:管理员' }
|
||
];
|
||
|
||
export default function FormModal({ visible = false, title = '表单', fields = DEFAULT_FIELDS, value = {}, onCancel, onSubmit }) {
|
||
const [form, setForm] = useState(value);
|
||
const [errors, setErrors] = useState({});
|
||
|
||
useEffect(() => {
|
||
if (visible) { setForm(value); setErrors({}); }
|
||
}, [visible]);
|
||
|
||
if (!visible) return null;
|
||
|
||
const onInput = (key, e) => {
|
||
setForm((f) => ({ ...f, [key]: e.target.value }));
|
||
setErrors((er) => { const n = { ...er }; delete n[key]; return n; });
|
||
};
|
||
const submit = () => {
|
||
const errs = {};
|
||
fields.forEach((f) => {
|
||
const v = (form[f.key] || '').trim();
|
||
if (f.required && !v) errs[f.key] = f.label + '不能为空';
|
||
if (f.key === 'email' && v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) errs[f.key] = '邮箱格式不正确';
|
||
});
|
||
if (Object.keys(errs).length) { setErrors(errs); return; }
|
||
if (onSubmit) onSubmit({ ...form });
|
||
if (onCancel) onCancel();
|
||
};
|
||
|
||
return (
|
||
<div className="aa-formmodal-mask" onClick={(e) => { if (e.target === e.currentTarget) onCancel && onCancel(); }}>
|
||
<div className="aa-formmodal">
|
||
<div className="aa-formmodal-head">
|
||
<span>{title}</span>
|
||
<button className="aa-formmodal-close" onClick={() => onCancel && onCancel()}>×</button>
|
||
</div>
|
||
<div className="aa-formmodal-body">
|
||
{fields.map((f) => (
|
||
<div className="aa-form-row" key={f.key}>
|
||
<label className="aa-form-label">
|
||
{f.required && <span className="req">*</span>}
|
||
{f.label}
|
||
</label>
|
||
<input
|
||
className={'aa-form-input' + (errors[f.key] ? ' is-error' : '')}
|
||
value={form[f.key] || ''}
|
||
placeholder={f.placeholder}
|
||
onChange={(e) => onInput(f.key, e)}
|
||
/>
|
||
{errors[f.key] && <div className="aa-form-err">{errors[f.key]}</div>}
|
||
</div>
|
||
))}
|
||
</div>
|
||
<div className="aa-formmodal-foot">
|
||
<button className="aa-btn" onClick={() => onCancel && onCancel()}>取消</button>
|
||
<button className="aa-btn aa-btn--primary" onClick={submit}>提交</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|