简体   繁体   中英

React set input value to object property not editable

I'm setting the value of an input to a property on an object (from the state). I have an onChange event to update the state. However, when I try to type, it doesn't actually update in the input. If I don't use an object and just have a string, it works fine. How can I fix this?

Demo of the issue
My code:

import React from "react";

export function App() {
  const [data, setData] = React.useState({
    test: "hello"
  });
  
  const change = (e) => {
    data.test = e.target.value;
    setData(data);
  };

  return <input value={data.test} onChange={change}></input>;
}

Per the comment by Aman Sadhwani , I used spread syntax to update the state without modifying the original object.

const change = (e) => {
    setData({
        ...data,
        test: e.target.value
    });
};

Thanks, @Aman Sadhwani. Use Spread operator to update the state.

import React from "react";

export function App() {
  const [data, setData] = React.useState({
    test: "hello"
  });
  
  const change = (e) => {
    setData({
    ...data
    test:e.target.value
    });
  };

  return <input value={data.test} onChange={change}></input>;
}

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