1. React开发环境准备
- 安装nodejs和npm:
下载地址https://nodejs.org/en/download - 安装成功后,查看版本
shangyudianzideMacBook-Pro:~ shangyudianzi$ npm -v 6.9.0 shangyudianzideMacBook-Pro:~ shangyudianzi$ node -v v10.16.0
-
创建项目,请执行:
https://zh-hans.reactjs.org/docs/create-a-new-react-app.htmlnpx create-react-app my-app cd my-app npm start
代码实现功能:添加表单,删除表单
TodoItem.js
import React, { Component } from 'react';
import PropTypes from 'prop-types'
class TodoItem extends Component {
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
render(){
const { content } = this.props
return (
<div onClick={this.handleClick}>
{content}
</div>
)
}
handleClick(){
const { deleteItem , index } = this.props
deleteItem(index)
}
}
TodoItem.propTypes = {
content:PropTypes.string.isRequired,
deleteItem:PropTypes.func,
index:PropTypes.number
}
TodoItem.defaultProps = {
content:'hello world'
}
export default TodoItem
TodoList.js
import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem'
import './style.css'
class TodoList extends Component {
constructor (props){
super(props);
this.state = {
inputValue : 'ddd',
list: []
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
this.handleItemDelete = this.handleItemDelete.bind(this)
}
render() {
return (
<Fragment>
<div>
<label htmlFor='insertArea'>输入内容</label>
<input
id='insertArea'
className='input'
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
<button onClick={this.handleBtnClick}>提交</button>
</div>
<ul>
{ this.getTodoItem() }
</ul>
</Fragment>
)
}
getTodoItem(){
return this.state.list.map((item,index) => {
return (
<TodoItem
key={index}
content={item}
index={index}
deleteItem={this.handleItemDelete}
/>
)
})
}
handleInputChange(e){
const value = e.target.value
this.setState(() => ({
inputValue:value
}))
}
handleBtnClick(){
this.setState((prevState) => ({
list:[...prevState.list,prevState.inputValue],
inputValue:''
}))
}
handleItemDelete(index){
this.setState((prevState) => {
const list = [...prevState.list];
list.splice(index,1)
return {list}
})
}
}
export default TodoList;
style.css
.input {
border: 1px solid red;
}
React有以下特性:
- 声明式开发
- 可以与其他框架并存
- 组件化
- 单向数据流
- 视图层框架
- 函数式编程