外贸自己做网站/百度seo招聘
React 入门笔记 做一个简单todolist
文章目录
- React 入门笔记 做一个简单todolist
- 安装react
- 精简代码
- 下面进行代码修改
第一步,看文档,不多说
安装react
环境准备:
- 安装node ,去官网下载安装,安装完自带npm包管理工具
根据官网教程,create react app
npx create-react-app my-app
cd my-app
npm start // or yarn start
npx 是一个帮你执行文件的工具
npx 会自动查找当前依赖包中的可执行文件,如果找不到,就会去 PATH 里找。如果依然找不到,就会帮你安装!
精简代码
打卡src
目录,只保留index.js
app.js
文件内的其他依赖都删掉,只保留 React
ReactDOM
相关的代码
index.js
是入口文件,修改后index.js
文件如下:
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';ReactDOM.render(<TodoList />, document.getElementById('root'));
原本的组件名<App />
改为了<TodoList />
修改app.js
重命名为TodoList.js
把原来的内容改为如下:
import React, { Component } from 'react'class TodoList extends Component {render() {return (<div>hello react</div>)}
}
export default TodoList
页面也可以正常运行,并在页面上显示出hello react
下面进行代码修改
用jsx语法写页面结构代码,代码经过优化
知识点:
- js的this绑定,写在dom上的方法this会指向dom元素,需要用
bind
绑定this
到class - es6语法,扩展运算符,解构赋值,对象属性简写
- 父组件通过参数的形式向子组件传递参数
- 子组件通过props接收父组件传递过来的参数
- 父子组件通信,子组件通过父组件传递过来的方法,触发父组件上绑定的方法,达到通信的目的
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 = {list: [],inputValue: ''}this.handleInputChange = this.handleInputChange.bind(this)this.handleBtnClick = this.handleBtnClick.bind(this)this.handleDelete = this.handleDelete.bind(this)}handleInputChange(e) {this.setState({inputValue: e.target.value})}handleBtnClick() {this.setState({list: [...this.state.list, this.state.inputValue],inputValue: ''})}handleItemClick(index) {console.log(index)const list = [...this.state.list]list.splice(index, 1)this.setState({list})}// 父组件通过属性的形式向子组件传递参数// 子组件通过props接收父组件传递过来的参数handleDelete(index) {console.log(index)const list = [...this.state.list]list.splice(index, 1)this.setState({list})}getTodoItem() {return this.state.list.map((item, index) => {return (<TodoItemdeleteItem={this.handleDelete}key={index}content={item}index={index}/>)})}render() {return (// Fragment 只作包裹作用,不会产生一个div<Fragment><inputvalue={this.state.inputValue}onChange={this.handleInputChange}/><button className="red-btn" onClick={this.handleBtnClick}>add</button><ul>{this.getTodoItem()}</ul></Fragment>)}
}export default TodoList
src
目录下新建一个TodoItem.js
import React from 'react'class TodoItem extends React.Component {constructor(props) {super(props)this.handleDelete = this.handleDelete.bind(this)}// 子组件如果想和父组件通信,子组件要调用父组件传递过来的方法handleDelete() {// console.log(this.props.index)// this.props.delete(this.props.index) //代码优化const {deleteItem, index} = this.propsdeleteItem(index)}render() {const {content} = this.propsreturn (<div onClick={this.handleDelete}>{content}</div>)}
}
export default TodoItem
完整代码demo: https://gitee.com/hotsuitor/react_demo.git
用过vue开发过项目,入门react,觉得react写起来真的爽