您当前的位置: 首页 >  前端

前端学习:React快速入门TodoList实例

彭世瑜 发布时间:2018-07-21 15:11:36 ,浏览量:4

安装环境

Node.js https://nodejs.org/ reactjs https://reactjs.org/

更换npm淘宝源

$ npm config set registry https://registry.npm.taobao.org
-- 配置后可通过下面方式来验证是否成功
$ npm config get registry

环境检查 windows shift+右键 在此处打开命令行窗口

$ node -v
$ npm -v
新建项目
$ npx create-react-app my-app
$ cd my-app
$ npm start

http://localhost:3000/

精简项目

src目录下以下文件都可以删除

registerServiceWorker.js
index.css
App.test.js
App.css
logo.svg
组件

网页中的一部分, 一般采用大写字母开头 定义一个组件需要继承React.Component 1. 必须有render 2. 花括号中可以写js表达式 3. 支持jsx语法,可以直接使用标签结构 4. render函数只能返回一个标签内容 5. 父组件通过属性给子组件传递参数 6. 子组件通过props接收父组件传递过来的参数 7. 思想:面向数据编程 8. 子组件如果要和父组件通讯,要调用父组件传递过来的方法 9. css样式类关键词使用className=”value”, style={{key: “value”}}

代码实例

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';

import "./style.css"

ReactDOM.render(, document.getElementById('root'));

TodoList.js

import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem.js';

// 定义一个组件
class TodoList extends Component {
  // 构造函数初始化
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      inputValue: ''
    };
    // 代码优化
    this.handleClick = this.handleClick.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleClick() {
    this.setState({
      // 展开运算符 es6
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
    })
  }

  handleInput(e) {
    this.setState({
      inputValue: e.target.value
    })
  }

  handleDelete(index) {
    // 拷贝一个副本出来,操作副本
    const list = [...this.state.list];
    list.splice(index, 1)
    this.setState({
      list: list
    })
  }

  getItemListByThis(index, item){
    return (
       {item}
    )
  }

  getTodoItems(){
      return (this.state.list.map((item, index)=>{
                return (
                  
                )
                }))}

  // 必须有render
  render() {
  // 花括号中可以写js表达式
    return (
      // jsx语法,可以直接使用标签结构
      
       
        
        {color: 点击
      
      
    { this.getTodoItems() }
); } } export default TodoList; //导出才可以导入

TodoItem.js

import React, {Component} from "react";

class TodoItem extends Component{

    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }
    //子组件接受参数props
    handleClick() {
        this.props.delete(this.props.index)
    }

    render() {
        const content = this.props.content
        return (
             {content} 
        );
    }
}

export default TodoItem;

style.css

.red-btn{
    background: red;
}

github地址:https://github.com/mouday/HTML/tree/master/react_demo

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 4浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0955s