- React是FaceBook旗下的前端框架, 特点是组件化, 高度封装,组件复用, 不足是视图与数据都被归到了render函数中,未达到数据与视图的分离
- React首创的JSP语法已经成为独立的标准, 被开源社区所认可, 与Vue模板语法相比, JSP的语法更加易读
- ReactApp的出现,更让前端程序员快速制作App成为了可能
安装运行React项目
通过npm全局安装,可以创建React的脚本
sudo npm install -g create-react-app
复制代码
创建React项目(项目名为react-to-do-list)
create-react-app react-to-do-list
复制代码
运行项目 react-to-do-list
cd react-to-do-list
npm start
复制代码
Todolist效果核心组件
import React, { Component } from 'react';
class Todo extends Component{
constructor(props){
super(props);
this.state = {
to_do_list:['a', 'b'],
title: ""
}
}
// 处理点击事件
clickHandle(){
// 获取当前title内容
let newTitle = this.state.title;
// 如果当前title内容为空, 则拒绝添加
if (newTitle.length === 0){
return
}
// 获取当前列表内容, 赋值到一个临时数组
let oldList = this.state.to_do_list;
// 将当前title内容添加到临时数组
oldList.push(newTitle)
// 更新to_do_list内容, 清空input内容
this.setState({
to_do_list: oldList,
title: ""
})
}
// 处理input值更新
inputHandle(event){
// 将新输入的文字,同步到title
const newTitle = event.target.value;
this.setState({
title: newTitle
})
}
render(){
let pStyle = {
padding: 10,
margin: 10,
backgroundColor: "#ffde00",
color: "#333",
display: "inline-block",
fontFamily: "monospace",
fontSize: "32",
textAlign: "left",
fontSize: 30,
};
let inputStyle = {
width : 300,
heigth: 20,
fontSize: 18
}
let btnStyle = {
width: 50,
heigth: 20,
fontSize: 18,
}
return (
<p style={pStyle}>React实现<br/>Todo任务列表<br/>
<input style={inputStyle} value={this.state.title} onChange={this.inputHandle.bind(this)}></input>
<button onClick = {this.clickHandle.bind(this)}>添加</button>
{this.state.to_do_list.map((item, index) => {
return <li key={index}>{item}</li>
}
)}
</p>
)
}
}
export default Todo
复制代码