【发布时间】:2021-02-13 16:25:38
【问题描述】:
我是 React 的新手。我有一个看似标准的任务:填写有关用户的表单数据并将其发送到服务器。表单是一组组件,如:基本信息、护照资料、爱好等+保存按钮。
我是通过以下方式做到的。有一个 class 描述该模型。创建组件时,我在useRef 中创建了这个class 的实例。此外,我通过它们的道具将这个model 变量传递给所有子组件。模型属性填充在组件中。所以当我点击Save 按钮时,我已经填写了模型属性。Here's an example。
请告诉我,这是填充复杂对象数据的好方法吗?也许以不同的方式做会更好?有没有最佳实践?也许我应该使用 redux 来完成这项任务?
model.ts
class Model {
// Component 1
firstName: string;
lastName: string;
// Component 2
passport: string;
address: string;
}
interface IComponent {
model: Model;
}
export { Model, IComponent };
index.tsx
export const App: React.FunctionComponent<{}> = () =>
{
const model = useRef<Model>(new Model());
const save = () =>{
console.log(model.current);
}
return (
<React.Fragment>
<Component1 model={model.current} />
<Component2 model={model.current} />
<button onClick={save}>Сохранить</button>
</React.Fragment>
);
}
render(<App />, document.getElementById('root'));
Component1.tsx
export const Component1: React.FunctionComponent<IComponent> = ({ model }) => {
const [firstNameValue, setFirstNameValue] = useState(model.firstName);
const [lastNameValue, setLastNameValue] = useState(model.lastName);
const changeFirstName = (e: React.ChangeEvent<HTMLInputElement>) => {
model.firstName = e.target.value;
setFirstNameValue(e.target.value);
}
const changeLastName = (e: React.ChangeEvent<HTMLInputElement>) => {
model.lastName = e.target.value;
setLastNameValue(e.target.value);
}
return (
<React.Fragment>
<div>
<label htmlFor="firstName">FirstName:</label>
<input name="firstName" value={firstNameValue} onChange={changeFirstName} />
</div>
<div>
<label htmlFor="lastName">LastName:</label>
<input name="lastName" value={lastNameValue} onChange={changeLastName}/>
</div>
</React.Fragment>);
};
Component2.tsx
export const Component2: React.FunctionComponent<IComponent> = ({ model }) => {
const [passportValue, setPassportValue] = useState(model.passport);
const [addressValue, setAddressValue] = useState(model.address);
const changePassport = (e: React.ChangeEvent<HTMLInputElement>) => {
model.passport = e.target.value;
setPassportValue(e.target.value);
}
const changeAddress = (e: React.ChangeEvent<HTMLInputElement>) => {
model.address = e.target.value;
setAddressValue(e.target.value);
}
return (
<React.Fragment>
<div>
<label htmlFor="passport">Passport:</label>
<input name="passport" value={passportValue} onChange={changePassport} />
</div>
<div>
<label htmlFor="address">Address:</label>
<input name="address" value={addressValue} onChange={changeAddress}/>
</div>
</React.Fragment>);
};
【问题讨论】:
-
我正在努力解决这个问题,但是在您的特定用例中是否有任何理由
Model必须是class实例而不是interface?特别是因为我们开始时所有属性都是空的,所以我真的不会在这里使用class。您可以在调用onSubmit时从数据中创建class。
标签: reactjs typescript forms state-management