我们正在使用mobx和react构建一个MVVM应用程序。目前,我们最好的选择是创建类似于这个简化示例的视图模型和UI组件。
// LoginModel.ts
export class LoginModel {
@observable
public userName: string;
@observable
public password: string;
}
// LoginView.tsx
@observer
export class LoginView extends React.Component<LoginViewProps> {
public render(): JSX.Element {
return (
<div>
<input type="text" value={this.model.userName} onChange={e => this.model.userName = e.value} />
<input type="password" value={this.model.password} onChange={e => this.model.password= e.value} />
</div>
);
}
}在此实现中,当userName或password更改时,组件将完全重新呈现。
我想要实现的是我们自己的自定义TextInput组件,它将负责呈现布局、样式、接收用户输入,以及显示基于模型状态的验证错误等。
value、onChange和例如error,并使用它类似于上面的示例。在这种情况下,问题是相同的,在单个可观察属性中的每一项更改都会重新呈现整个“表单”组件。这是因为我并没有取消TextInput组件中可观察到的内容,而是在TextInput中,比如model: any和field: string中使用model[field]。这样,我就可以在TextInput中进行取消引用,它可以正常工作,但是我会丢失一些强类型和TextInput。几个注意事项:
react-forms等库。Provider和@inject模式,我喜欢显式。有人能给我一些关于这种情况的想法和建议吗?
发布于 2020-07-06 08:39:35
mobx有非常棒的表单库,它使用非常类似的技术https://formstate.github.io,您可能可以从它复制此模式。
发布于 2022-03-24 10:45:24
您可以使用对象而不是普通字符串。
interface Str{
value:string
}然后可以在输入组件中使用.value。
https://stackoverflow.com/questions/62750658
复制相似问题