【问题标题】:Change input values bases on other input onChange根据其他输入 onChange 更改输入值
【发布时间】:2021-01-17 23:33:53
【问题描述】:

假设我要创建一个Converter,这意味着输入值应该根据另一个改变。

只是看看我想在行动中做什么https://calolocosta.github.io/romanNumeralsConverter/

这是我迄今为止尝试过的,但无法成功

function LightBulb() {
  let [input1, setInput1] = useState("");
  let [input2, setInput2] = useState("");

  const handleInput1 = (e) => {
    setInput2(e.target.value);
  };

  const handleInput2 = (e) => {
    setInput1(e.target.value);
  };

  return (
    <div className="App">
      <input
        type="text"
        value={input2}
        onChange={(e) => handleInput1(e)}
        placeholder="example 1000"
      />
      <input
        type="text"
        value={input1}
        onChange={(e) => handleInput2(e)}
        placeholder="example MCMXC"
      />
    </div>
  );
}

所以我想要的是在 input1 键入时更改 input2 的值,反之亦然。 这是我一直在研究的代码框:https://codesandbox.io/s/react-hooks-usestate-forked-8o257,任何想法都会不胜感激。

【问题讨论】:

    标签: reactjs forms react-hooks


    【解决方案1】:

    我想您会为该转换执行其余的逻辑。但就输入及其需要更改另一个的交互而言,这里是更改的代码:

    function LightBulb() {
      let [input1, setInput1] = useState("");
      let [input2, setInput2] = useState("");
    
      const handleInput1 = (e) => {
        setInput1(e.target.value);
        setInput2("Converted value");
      };
    
      const handleInput2 = (e) => {
        setInput2(e.target.value);
        setInput1("Converted value");
      };
    
      console.log(input2);
    
      return (
        <div className="App">
          <input
            type="text"
            value={input1}
            onChange={(e) => handleInput1(e)}
            placeholder="example 1000"
          />
          <input
            type="text"
            value={input2}
            onChange={(e) => handleInput2(e)}
            placeholder="example MCMXC"
          />
        </div>
      );
    }
    

    无论如何,您都需要为相应的输入设置值。但是对方的值需要用转换后的值来设置。

    这里还有codesandbox:https://codesandbox.io/s/react-hooks-usestate-forked-667fr?file=/src/index.js:100-777

    【讨论】:

    • 感谢马里奥的帮助。
    • Np。很高兴我帮了忙。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2019-07-20
    • 1970-01-01
    • 2016-10-13
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多