Создадим первый проект и установим через Nuget React.Web.Mvc4
Воспользуемся контроллером Home и его методом Index
1 2 3 4 |
public ActionResult Index() { return View(); } |
В его представлении напишем следующее
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@{ Layout = null; } <html> <head> <title>Hello React</title> </head> <body> <div id="content"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script> <script src='@Url.Content("~/Scripts/helloApp.jsx")'></script> </body> </html> |
В скрипты добавим следующий файл helloApp.jsx
1 2 3 4 5 6 7 8 9 |
class Hello extends React.Component { render() { return <h1>Привет, React.JS</h1>; } } ReactDOM.render( <Hello />, document.getElementById("content") ); |
Результат
Пример с телефонами
Допишем в контроллер следующие методы
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public ActionResult Phones() { return View(); } static List<Phone> data = new List<Phone> { new Phone { Id = Guid.NewGuid().ToString(), Name="iPhone 7", Price=52000 }, new Phone { Id = Guid.NewGuid().ToString(), Name="Samsung Galaxy S7", Price=42000 }, }; public ActionResult GetPhones() { return Json(data, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult AddPhone(Phone phone) { phone.Id = Guid.NewGuid().ToString(); data.Add(phone); return Json(phone); } [HttpDelete] public ActionResult DeletePhone(string id) { Phone phone = data.FirstOrDefault(x => x.Id == id); if (phone != null) { data.Remove(phone); return Json(phone); } return HttpNotFound(); } |
Представление
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@{ Layout = null; } <html> <head> <title>Hello React</title> </head> <body> <div id="content"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script> <script src='@Url.Content("~/Scripts/helloApp2.jsx")'></script> </body> </html> |
Скрипт helloApp2.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
class Phone extends React.Component { constructor(props) { super(props); this.state = { data: props.phone }; this.onClick = this.onClick.bind(this); } onClick(e) { this.props.onRemove(this.state.data); } render() { return <div> <p><b>{this.state.data.Name}</b></p> <p>Цена {this.state.data.Price}</p> <p><button onClick={this.onClick}>Удалить</button></p> </div>; } } class PhoneForm extends React.Component { constructor(props) { super(props); this.state = { name: "", price: 0 }; this.onSubmit = this.onSubmit.bind(this); this.onNameChange = this.onNameChange.bind(this); this.onPriceChange = this.onPriceChange.bind(this); } onNameChange(e) { this.setState({ name: e.target.value }); } onPriceChange(e) { this.setState({ price: e.target.value }); } onSubmit(e) { e.preventDefault(); var phoneName = this.state.name.trim(); var phonePrice = this.state.price; if (!phoneName || phonePrice <= 0) { return; } this.props.onPhoneSubmit({ name: phoneName, price: phonePrice }); this.setState({ name: "", price: 0 }); } render() { return ( <form onSubmit={this.onSubmit}> <p> <input type="text" placeholder="Модель телефона" value={this.state.name} onChange={this.onNameChange} /> </p> <p> <input type="number" placeholder="Цена" value={this.state.price} onChange={this.onPriceChange} /> </p> <input type="submit" value="Сохранить" /> </form> ); } } class PhonesList extends React.Component { constructor(props) { super(props); this.state = { phones: [] }; this.onAddPhone = this.onAddPhone.bind(this); this.onRemovePhone = this.onRemovePhone.bind(this); } // загрузка данных loadData() { var xhr = new XMLHttpRequest(); xhr.open("get", this.props.getUrl, true); xhr.onload = function () { var data = JSON.parse(xhr.responseText); this.setState({ phones: data }); }.bind(this); xhr.send(); } componentDidMount() { this.loadData(); } // добавление объекта onAddPhone(phone) { if (phone) { var data = new FormData(); data.append("name", phone.name); data.append("price", phone.price); var xhr = new XMLHttpRequest(); xhr.open("post", this.props.postUrl, true); xhr.onload = function () { if (xhr.status == 200) { this.loadData(); } }.bind(this); xhr.send(data); } } // удаление объекта onRemovePhone(phone) { if (phone) { var data = new FormData(); data.append("id", phone.Id); var xhr = new XMLHttpRequest(); xhr.open("delete", this.props.deleteUrl, true); xhr.onload = function () { if (xhr.status == 200) { this.loadData(); } }.bind(this); xhr.send(data); } } render() { var remove = this.onRemovePhone; return <div> <PhoneForm onPhoneSubmit={this.onAddPhone} /> <h2>Список смартфонов</h2> <div> { this.state.phones.map(function (phone) { return <Phone key={phone.Id} phone={phone} onRemove={remove} /> }) } </div> </div>; } } ReactDOM.render( <PhonesList getUrl="/home/getphones" postUrl="/home/addphone" deleteUrl="/home/deletephone" />, document.getElementById("content") ); |
Результат