【问题标题】:Getting undefined instead of Input Field value获取未定义而不是输入字段值
【发布时间】:2021-12-09 17:40:27
【问题描述】:
import { useState } from "react";
import "./styles.css";

function App() {
  const [InputVal, setInputVal] = useState();
  const [ShowDiv, setShowDiv] = useState(
    <div>
      <p>Hello world. This is default "Show Div" value</p>
    </div>
  );

  const ChangeDivFunc = () => {
    setShowDiv(
      <div>
        <p style={{ color: "red" }}>
          Hello World. This is updated "Show Div" value
        </p>
        <input onChange={getInputval} type="text" />
        <br />
        <br />
        <button onClick={AlertVal}>Show Input Value</button>
      </div>
    );
  };

  const getInputval = (val) => {
    setInputVal(val.target.value);
  };

  const AlertVal = () => {
    alert(InputVal);
  };

  return (
    <div className="App">
      <h1>Example</h1>
      <br />
      <button onClick={ChangeDivFunc}>Change Div</button>
      {ShowDiv}
    </div>
  );
}

export default App;

代码流:

  1. 点击Change Div按钮会显示Input fieldShow Input Value按钮。
  2. 现在,在input field中输入一些值,然后点击Show Input Value按钮来获取input field的值。

问题: 它返回 undefined 而不是 input field 值。

当点击显示输入值按钮时,我正在尝试获取输入字段的值。但我没有得到想要的结果。

这里是沙盒链接:Click for Code

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    不要将 html 节点存储在状态中。您可以只存储一个布尔值来在要显示的节点之间切换。我不太确定,但它可能会导致奇怪的行为,因为 React 内部在很大程度上依赖于 DOM/HTML UI 树(请参阅Managing State)。

    试试这个:

    import { useState } from "react";
    import "./styles.css";
    
    function App() {
      const [inputVal, setInputVal] = useState("");  // initialize as empty string.
      const [showDiv, setShowDiv] = useState(false);
    
      const changeDivFunc = () => {
        setShowDiv(true);
      };
    
      const getInputVal = (event) => {  // The arg is Event object, not val
        setInputVal(event.target.value);
      };
    
      const alertVal = () => {
        alert(inputVal);
      };
    
      return (
        <div className="App">
          <h1>Example</h1>
          <br />
          <button onClick={changeDivFunc}>Change Div</button>
          {
            showDiv? (
              <div>
                <p style={{ color: "red" }}>
                   Hello World. This is updated "Show Div" value
                </p>
                <input value={inputVal} onChange={getInputVal} type="text" />
                <br />
                <br />
                <button onClick={alertVal}>Show Input Value</button>
              </div>
            ) : (
              <div>
                <p>Hello world. This is default "Show Div" value</p>
              </div>
            )
          }
        </div>
      );
    }
    
    export default App;
    

    Forked Codepen

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2013-09-26
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多