简体   繁体   English

输入显示占位符而不是值

[英]Input showing placeholder instead of value

I am having trouble to set the input to show the placeholder instead of displaying the value from state.我无法将输入设置为显示占位符而不是显示 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>

Is there something I can do in onChange or onClick where the user can just enter their values without having to delete the initial 0 first?我可以在 onChange 或 onClick 中做些什么,用户只需输入他们的值而不必先删除初始 0 吗?

The initial value is 0, so it will show up in the field.初始值为 0,因此它会显示在该字段中。 Empty string might work.空字符串可能有效。

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

The above snippet was for demo, you just need to change the value of age property in your code.上面的代码片段用于演示,您只需要在代码中更改age属性的值即可。

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

This is the answer if you want the age in the state to start with 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>

You can set the initial value like the way you we're doing, but to change as the user types a new age you could do this:您可以像我们正在做的那样设置初始值,但是要随着用户键入新的年龄而改变,您可以这样做:

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

; ;

const [infoValue, setInfoValue] = useState(initialState) 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