简体   繁体   English

无法更改输入标签的值

[英]Not being able to change the value of input tag

So I'm trying to set the default value of input tag to a state but when I do so I'm unable to change anything in the input tag, The text just gets stuck, Here is an example of my code:所以我试图将输入标签的默认值设置为 state 但是当我这样做时,我无法更改输入标签中的任何内容,文本卡住了,这是我的代码示例:

function RandomScreen(){
    const [State, SetState] = useState()
    // Make API call to set the state
    const inputValue = State
    return(
        <input onChange={handleState} value={inputValue} />
    )
}

I'm using onChange but did not want to include it to reduce noise and to minimize code.我正在使用onChange但不想包含它以减少噪音并最小化代码。

You need onChange function to change value of input您需要onChange function 来更改input

Try something like below:-试试下面的东西: -

function RandomScreen(){
    const [inputState, setInputState] = useState('');
   
    return(
        <input value={inputState} onChange={(e) => setInputState(e.target.value)}/>
    )
}

You are not seeing the changes in Input because you are making the input controlled and not updating the state.您看不到输入中的更改,因为您正在控制输入并且没有更新 state。

Try doing this:尝试这样做:

function RandomScreen(){
    const [input, setInput] = useState();
    const onChange = e => {
      // call API here
    setInput(e.target.value)
    }

    return(
        <input value={input} onChange={onChange} />
    )
}

Read more about controlled components here: https://reactjs.org/docs/forms.html#controlled-components在此处阅读有关受控组件的更多信息: https://reactjs.org/docs/forms.html#controlled-components

For making API call you can also take use of useEffect hook.要进行 API 调用,您还可以使用useEffect挂钩。

You have to write an event handler called onChange which will update the state as you type.您必须编写一个名为onChange的事件处理程序,它将在您键入时更新 state。 Here is a slightly changed and updated code -这是一个稍微更改和更新的代码 -

function RandomScreen(){
const [inputValue, setInputValue] = useState('')
// Make API call to set the state
return(
    <input value={inputValue} onChange={(event) => setInputValue(event.target.value)} />
)

} }

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

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