【问题标题】:Why input value does not change when we pass null or undefined as a value?为什么当我们将 null 或 undefined 作为值传递时输入值不会改变?
【发布时间】:2021-12-23 00:36:04
【问题描述】:

在使用受控输入组件时,如果我们将受控组件的值设置为 null 或 undefined,则之前的值仍会显示在 UI 上,而不是更改它,并且保持该输入值的状态会更改为 null 或 undefined。我创建了一个沙盒以便更好地理解

https://codesandbox.io/s/black-architecture-0wqw1

谢谢

【问题讨论】:

    标签: html reactjs forms


    【解决方案1】:

    这里是快速修复,它永远不会更改值变量,如果数据然后将数据放入空字符串,它是如何工作的

    <input
        type="text"
        onChange={(e) => setData(e.target.value)}
        value={data ? data:""}
      />
    

    我希望这能解决你的问题, 这是完整的修复, https://codesandbox.io/embed/optimistic-currying-snn8t?fontsize=14&hidenavigation=1&theme=dark

    【讨论】:

      【解决方案2】:

      如果数据类型是nullundefined,则自动做出反应,抑制该值并且不记录任何内容。

      如果您想查看该特定值的类型,请写{typeof data},然后您就会得到答案。

      ...
      setData(null)
      typeof data // object
      
      setData("hi")
      typeof data // string
      
      setData(undefined)
      typeof data // undefined
      ...
      

      【讨论】:

        【解决方案3】:

        您可以在输入组件之外的任何地方使用 ref tout 更改输入的值,见下文:

        import React, { useState, useEffect } from "react";
        import "./styles.css";
        
        export default function App() {
          const [data, setData] = useState(null);
          const inputRef = React.useRef(null);
          useEffect(() => {
            console.log(data);
          }, [data]);
        
          return (
            <div className="App">
              <h1>Hello CodeSandbox</h1>
              <h2>Start editing to see some magic happen!</h2>
              <input
              ref={inputRef}
                type="text"
                onChange={(e) => setData(e.target.value)}
                value={data}
              />
              <div style={{ marginTop: "10px" }}>
                <button onClick={() => {
                  setData(null);
                  inputRef.current.value = ''
                  }}>SET DATA NULL</button>
              </div>
              <div style={{ marginTop: "10px" }}>
                <button onClick={() => {
                  setData(undefined)
                  inputRef.current.value = ''
                  }}>
                  SET DATA UNDEFINED
                </button>
              </div>
              <div style={{ marginTop: "10px" }}>INPUT VALUE {data}</div>
            </div>
          );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-15
          • 1970-01-01
          • 2021-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-26
          • 1970-01-01
          相关资源
          最近更新 更多