使用vue+react实现一个根据上方input输入的数字,下面对应展示相应数量的input输入框(二)

53 阅读1分钟

Snipaste_2023-04-09_23-12-39.png

补充下:还需要实现删除层数后,再次输入层数,如果包含原来的层数,那么原来的数据还是需要保留的

我们接着上次的问题进行学习:

3.react+class组件实现

import React, { PureComponent } from "react";
export default class Count extends PureComponent {
  state = {
    resAry: [],
    ary: [],
  };
  myInput = React.createRef();
  handleChange = (e) => {
    const num = Number(e.target.value);
    let tempAry = [];
    console.log("33333", this.state.ary);
    if (this.state.ary && num < this.state.ary.length && num !== 0) {
      tempAry = this.state.ary.slice(0, num);
      this.setState({ resAry: tempAry });
      // 这个地方还需要在更新下辅助的参数,为了解决先输入3-2-5这样的情况的出现的问题
      this.setState({ ary: tempAry });
      return;
    }
    if (this.state.ary && num > this.state.ary.length) {
      tempAry = [...this.state.ary];
      // 定义初始值
      for (let i = this.state.ary.length; i < num; i++) {
        const item = {
          id: i + Math.random(),
          val: "",
        };
        tempAry[i] = item;
      }
      this.setState({ resAry: tempAry });
      return;
    }

    for (let i = 0; i < num; i++) {
      const item = {
        id: i + Math.random(),
        val: "",
      };
      tempAry[i] = item;
    }
    this.setState({ resAry: tempAry });
  };
  handleChangeItem = (e, idx) => {
    let tempAry = this.state.resAry;
    tempAry[idx].val = e.target.value;
    this.setState({ resAry: tempAry });
    // 增加一个变量为了解决重新输入层数还保持原来的层数的数据
    this.setState({ ary: tempAry });
  };
  handleClick = () => {
    // 请求的参数
    console.log(this.state.resAry);
  };
  handleCancel = () => {
    // 将参数重置即可
    this.setState({
      ary: [],
      resAry: [],
    });
    this.myInput.current.value = "";
  };
  render() {
    const { resAry } = this.state;
    return (
      <>
        <div>
          层数:
          <input
            type="text"
            placeholder="请输入层数"
            onChange={this.handleChange}
            ref={this.myInput} //react中使用ref
          />
        </div>
        {resAry.map((item, index) => {
          return (
            <li key={item.id}>
              第{index + 1}层
              <input
                type="text"
                //  这里要使用defaultValue,不然会出现input框值不能输入的情况
                defaultValue={item.val}
                // 这个地方需要注意一下,需要传递参数的话,需要写成这个形式的
                onChange={(event) => this.handleChangeItem(event, index)}
                autoComplete="off"
              />
            </li>
          );
        })}
        <button onClick={this.handleClick}>发送请求</button>
        <button onClick={this.handleCancel}>取消</button>
      </>
    );
  }
}

4.react+hooks写法,使用hooks就比使用class类式组件丝滑多了

import React, { useState, useRef } from "react";
// 使用react+hooks来实现
const Hello = () => {
  const [ary, setAry] = useState([]);
  const [res, setRes] = useState([]);
  const myinput = useRef(null);
  const handleChnage = (e) => {
    const num = Number(e.target.value);
    if (res && num < res.length && num !== 0) {
      let tempAry = res.slice(0, num);
      setRes(tempAry);
    }
    let tempAry = new Array(num).fill("");
    setAry(tempAry);
  };
  const handleChangeItem = (e, idx) => {
    let tempAry = res;
    tempAry[idx] = e.target.value;
    setRes(tempAry);
  };
  const handleClick = () => {
    // /发送请求参数
    console.log(res);
  };
  const handleCancel = () => {
    setAry([]);
    setRes([]);
    myinput.current.value = "";
  };
  return (
    <div>
      <div>
        层数:
        <input
          type="text"
          placeholder="请输入层数"
          onChange={handleChnage}
          ref={myinput}
        />
      </div>
      {ary.map((_, index) => {
        return (
          <li key={index}>
            第{index + 1}层
            <input
              type="text"
              // 这个地方需要使用defaultValue
              defaultValue={res[index]}
              onChange={(e) => handleChangeItem(e, index)}
            />
          </li>
        );
      })}
      <button onClick={handleClick}>发送请求</button>
      <button onClick={handleCancel}>取消</button>
    </div>
  );
};

export default Hello;

这个小案例到这就结束,欢迎交流学习