繁体   English   中英

输入显示占位符而不是值

[英]Input showing placeholder instead of value

我无法将输入设置为显示占位符而不是显示 state 中的值。

  const initialState = [
    {
      name: "Chris",
      age: 0,
      height: 0,
      weight: 0,
    },
  ];

const [infoValue, setInfoValue] = useState(initialState)

    <div>
     <input type="number" placeholder={0} value={infoValue.age} onClick={} onChange={} />
    </div>

我可以在 onChange 或 onClick 中做些什么,用户只需输入他们的值而不必先删除初始 0 吗?

初始值为 0,因此它会显示在该字段中。 空字符串可能有效。

 <input type="number" placeholder="0" value="" />

上面的代码片段用于演示,您只需要在代码中更改age属性的值即可。

 const initialState = [
    {
      name: "Chris",
      age: '',
      height: 0,
      weight: 0,
    },
  ];

如果您希望 state 中的年龄以 0 开头,这就是答案。

     const initialState = [
    {
      name: "Chris",
      age: 0,
      height: 0,
      weight: 0,
    },
  ];

const [infoValue, setInfoValue] = useState(initialState)

    <div>
     <input type="number" placeholder={0} value={infoValue.age||''} onClick={} onChange={} />
    </div>

您可以像我们正在做的那样设置初始值,但是要随着用户键入新的年龄而改变,您可以这样做:

  const initialState = {
  name: "Chris",
  age: 0,
  height: 0,
  weight: 0,
  },

;

const [infoValue, setInfoValue] = useState(initialState)

<div>
 <input type="number" placeholder={0} value={infoValue.age} onChange={(e) => setInfoValue({...infoValue, age: e.target.value )} />
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM