几天前,我开始学习React,对此我并不陌生,在此之前,我在客户端使用Angular,在服务器端使用.net核心mvc和c#。
具有Html视图的动态数据绑定以及数据验证,当我使用“ Angular”时,它看起来非常舒适,但是当我切换到“ React”时,我却变得盲目。还有
我找不到任何将数据模型与Internet视图绑定的方法
我发现了什么?
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; }
}
通过this.state
传递此.cs数据模型,并将其与视图绑定。
是否可以做出反应,如果是,请提供解决方案。
答案 0 :(得分:0)
我希望我能很好地理解操作问题:
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);