简体   繁体   中英

React input onChange not rerendering state when useState has default value

So this is working, input changes when I type.

const [editfield, setEdit_field] = React.useState();

    function updateField(event) {
        setEdit_field(event.target.value);
    }

    function editPost() {
        setPostbody(<div><input onChange={updateField} value={editfield}></input></div>)
    }

But when a put a default value in the useState it doesnt work anymore

const [editfield, setEdit_field] = React.useState(post.body);

    function updateField(event) {
        setEdit_field(event.target.value);
    }

    function editPost() {
        setPostbody(<div><input onChange={updateField} value={editfield}></input></div>)
    }

Access code here: https://codesandbox.io/s/brt7ok

You are rendering that function so when state will updated it re-run that function and resetting the value.

You can use below approach. Take one state which represents the field is editable or not. And add condition with input component that it should only render when field is editable.

For example,

const [isEditable, setIsEditable] = useState(false);

<button onClick={() => setIsEditable(!isEditable)}>edit</button>

isEditable && (
    <div>
        <input onChange={updateField} value={editfield} />    
    </div>
)

For more idea, just put console before return . You will get idea.

Hope this helps :)

您在状态内设置 JSX,这可能是问题所在,我创建了一个代码沙盒演示,它将帮助您进行条件渲染演示

import React, { useState } from "react";

export default function App() {
let body = "hello";

const [editfield, setEditfield] = useState(body);
const [visible, setVisible] = useState(false);

function updateField(event) {
setEditfield(event.target.value);
}

function editPost() {
 setVisible(true);
}
return (
 <div>
  <div>{visible?<div>
    <input onChange={updateField} value={editfield}/>
  </div>:body}</div>
  <div>
    <button onClick={editPost}>edit</button>
  </div>
 </div>
);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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