首页 > 解决方案 > 如何动态绑定具有“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.stateuser两个属性,这些属性将与文本框中的视图绑定和验证,如下所示:

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并与视图绑定。

是否可以做出反应,如果可以,请提供解决方案。

标签: c#reactjsmodel-binding

解决方案


我希望我能很好地理解操作问题:

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);


推荐阅读