|
- import React, { Fragment, Component } from 'react';
- import './App.css';
- class Mytest extends Component {
- // 第一步 在所有函数之前执行的函数
- // 这是固定写法??? what why
- constructor(props) {
- super(props);
- // 所有的数据 都在 state里
- this.state = {
- inputValue: '',
- list: []
- }
- }
- render() {
- return (
- <Fragment>
- <div className="Mytest">
- <input
- value={this.state.inputValue}
- onChange={this.hand.bind(this)}
- onKeyDown ={this.handleKey.bind(this)}
- // 这里的 bind(this) 表示在该函数中重新制定该this对象 为 类本身
- type="text" />
- <button onClick={this.handleBtnClick.bind(this) } >提交</button>
- </div>
- <ul>
- {
- this.state.list.map((item, index) => {
- // 如果此处不加 key 值 控制台会给警告: 列表中每个内容都得有个独特的key
- // 这里这个 bind 里,绑定this 还可以传递一个索引值 index
- return (
- <li key = {index} onClick={this.handleLiClick.bind(this,index)}>
- {item}
- </li>
- );
- })
- }
- </ul>
- </Fragment>
- );
- }
- hand(e) {
- // 默认接受事件对象 e ,
- // e.target 为所操作的Dom
- // e.target.value 为所操作的value 值
- console.log(e.target.value)
- // this.state.inputValue =e.target.value;错误写法
- // 直接指定this.state 的值 并不能 改变其value的值 ,需要通过this.setState()
- this.setState({
- inputValue: e.target.value
- })
- }
- // 回车事件,我自己瞎几把测的
- handleKey(e)
- {
- // console.log(e.keyCode)
- //
- if(e.keyCode==13)
- {
- this.handleBtnClick();
- }
- }
- // 提交事件
- handleBtnClick()
- {
- this.setState({
- list:[...this.state.list,this.state.inputValue],
- inputValue:''
- })
- // 这里 虽然视频没讲 ,但是有一个逻辑顺序在里面 就是 从上往下 ,才能实现input 的清空
- }
- // 删除事件
- handleLiClick(index)
- {
- let listCopy = [...this.state.list];
- listCopy.splice(index,1);
- // 为什么要先复制一份数组呢, 是因为react 有个Immutable 规定 [ 就是在创建新数据时 要保证旧数据仍然可用的规定 ]
- // Immutable 参考地址 https://www.cnblogs.com/chris-oil/p/8494337.html
- this.setState({
- list:listCopy
- })
- }
- }
- export default Mytest;
复制代码
|
|