c# - 如何动态绑定具有“React”状态的数据模型?
问题描述
几天前我开始学习 React,对此我不太熟悉,在此之前我使用 Angular 作为客户端,使用 .net core mvc 和 c# 作为服务器端。
与 Html 视图的动态数据绑定以及数据验证,当我使用“Angular”时它看起来很舒服,但当我切换到“React”时,我变得盲目了。和
我找不到任何方法将数据模型与互联网上的视图绑定
我发现了什么?
class RegisterPage extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {
firstName: '',
lastName: ''
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
其中用户this.state
有user
两个属性,这些属性将与文本框中的视图绑定和验证,如下所示:
render() {
const { user } = this.state;
return (
<form name="form" onSubmit={this.handleSubmit}>
<input type="text" className="form-control" name="firstName" value={user.firstName} onChange={this.handleChange} />
{!user.firstName &&
<div className="help-block">First Name is required</div>
}
<input type="text" className="form-control" name="lastName" value={user.lastName} onChange={this.handleChange} />
{!user.lastName &&
<div className="help-block">Last Name is required</div>
}
</form>
</div>
);
}
我想要的是?
public class UserModel
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
传递这个 .cs 数据模型this.state
并与视图绑定。
是否可以做出反应,如果可以,请提供解决方案。
解决方案
我希望我能很好地理解操作问题:
class UserModel {
constructor(Id, FirstName, LastName) {
this.Id = Id;
this.FirstName = FirstName;
this.LastName = LastName;
}
get id() {
return this.Id;
};
get firstName() {
return this.FirstName;
};
get lastName() {
return this.LastName;
};
set id(newId) {
this.Id = newId; // validation could be checked here such as only allowing non numerical values
}
set firstName(newName) {
this.FirstName = newName; // validation could be checked here such as only allowing non numerical values
}
set lastName(newSurname) {
this.LastName = newSurname; // validation could be checked here such as only allowing non numerical values
}
get instance() {
return ({
id: this.Id,
firstName: this.FirstName,
lastName: this.LastName,
})
}
}
const user = new UserModel(1, 'John', 'Doe');
console.log(user.id);
console.log(user.firstName);
console.log(user.lastName);
console.log(user.instance);
推荐阅读
- html - 从 tesco HTML Xcode Swift4 中获取成分信息
- angular - 更新 webpack 和 Angular 后收到错误 Cannot find name 'setImmediate'
- excel - 具有最小差异百分比的工作表更改事件
- python - 在 PySpark 中读取 XML 文件
- java - 显示链表的第一个节点
- r - 使用 str_replace_all 将 / 替换为 \
- c - 当函数定义包含“*”时,带有默认“{{{”标记的“fold-create-marker”无法正常工作
- javascript - 2 个画布上的 globalCompositeOperation
- python - 如何在没有 pip install 的情况下导入 python 包
- reinforcement-learning - Q-Learning 中级奖励