【问题标题】:How do I get input onchange results without submit?如何在不提交的情况下获得输入 onchange 结果?
【发布时间】:2021-08-06 01:14:29
【问题描述】:

我尝试使用 useState 获取 onChange 值,我应该循环输入标签 但是标签看起来一样,没有人知道要添加多少输入,所以我想做的是在没有提交按钮的情况下推送数组。

这是测试代码,我要映射到它 我试着这样做:

import React, { useState } from "react";

const Test = () => {
  const [labelName, setLabelName] = useState("");
  const [labelContainer, setLabelContainer] = useState([]);

  const getTextValue = e => {
    setLabelName(e.target.value);
    setLabelContainer([...labelContainer, labelName]);
  };
  return (
    <div>
      num1 YAXIS:
      <input type="text" onChange={getTextValue} />
      num2 YAXIS:
      <input type="text" onChange={getTextValue} />
      num3 YAXIS:
      <input type="text" onChange={getTextValue} />
      <h1>num1 YAXIS:{labelContainer[0]}</h1>
      <h1>num2 YAXIS:{labelContainer[1]}</h1>
      <h1>num3 YAXIS:{labelContainer[2]}</h1>
    </div>
  );
};

export default Test;

但我无法得到每个结果。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这是你需要的吗?

    import React, { useState } from "react";
    export default function Test(props){
      const [labelName, setLabelName] = useState("");
      const [labelContainer, setLabelContainer] = useState([]);
    
      const getTextValue = (e,index) => {
        setLabelName(e.target.value);
        let temp=JSON.parse(JSON.stringify(labelContainer));
        temp[index]=e.target.value;
        setLabelContainer(temp);        
      };
      return (
        <div>
          num1 YAXIS:
          <input type="text" onChange={(e)=>getTextValue(e,0)} />
          num2 YAXIS:
          <input type="text" onChange={(e)=>getTextValue(e,1)} />
          num3 YAXIS:
          <input type="text" onChange={(e)=>getTextValue(e,2)} />
          <h1>num1 YAXIS:{labelContainer[0]}</h1>
          <h1>num2 YAXIS:{labelContainer[1]}</h1>
          <h1>num3 YAXIS:{labelContainer[2]}</h1>
        </div>
      );
    }

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 2017-06-08
      • 2012-10-11
      • 1970-01-01
      • 2021-05-04
      • 2018-06-07
      • 2017-12-29
      • 2013-11-20
      相关资源
      最近更新 更多