关于react.js:初探React

4次阅读

共计 1744 个字符,预计需要花费 5 分钟才能阅读完成。

1、创立 react 我的项目

npx create-react-app my-app(npx 是 npm 5.2+ 附带的 package 运行工具)
index.js为入口文件


2、启动我的项目

npm start


3、jsx 语法

能够利用 {} 写 js 表达式,如:{1 + 2}
不能写 js 语法 if 等,


4、函数 this

函数要通过上面 bind(this)绑定 TodoList 组件
this.handleBtnClick = this.handleBtnClick.bind(this)


5、父子组件传值

父组件通过属性传值;如:content={item} index={index}
react 根部只能有一个元素包裹,Fragmentreact 的片段,在页面中不显示;能够用于根部有两个或者多个元素

import React from "react";
import TodoItem from "./TodoItem";
class TodoList extends React.Component {constructor(props) {super(props);
    this.state = {list: [],
      inputValue: "",
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleDlete = this.handleDlete.bind(this);
  }
  handleBtnClick() {
    this.setState({list: [...this.state.list, this.state.inputValue],
      inputValue: "",
    });
  }
  handleInputChange(e) {
    this.setState({inputValue: e.target.value,});
  }
  handleDlete(index) {const list = [...this.state.list];
    list.splice(index, 1);
    this.setState({list,});
  }
  getTodoItems() {return this.state.list.map((item, index) => {
      return (
        <TodoItem
          content={item}
          key={index}
          index={index}
          delete={this.handleDlete}
        ></TodoItem>
      );
    });
  }
  render() {
    return (
      <React.Fragment>
        <div>
          <input
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          ></input>
          <button className="red-btn" style={{borderRadius:'2px',padding:'5px 10px'}} onClick={this.handleBtnClick}>add</button>
        </div>
        <ul>{this.getTodoItems()}</ul>
      </React.Fragment>
    );
  }
}

export default TodoList;

子组件通过 props 接管;如const {index} = this.props;

import React from "react";

class TodoItem extends React.Component {constructor(props) {super(props);
    this.handleDelete = this.handleDelete.bind(this);
  }
  handleDelete() {this.props.delete(this.props.index);
    // const {delete , index} = this.props;
    // delete index;
  }
  render() {const { content} = this.props;
    return <div onClick={this.handleDelete}>{content}</div>;
  }
}

export default TodoItem;

正文完
 0