If, after rendering, you start entering text into the input, then everything is OK, but after clicking on the "fill" button and automatically filling in the fields, it is no longer possible to change their values
Please tell me where is the mistake
import React, {useState} from "react";
const Test = () => {
const [item, setItem] = useState({});
const updateItem = (e) => {
item[e.target.id] = e.target.value;
setItem(item);
}
const aaa = () => {
let item = {
link : 'testlink',
title : 'testtitle',
desc : 'testdesc'
}
setItem(item);
}
return (
<form>
<input type="text" name="link" id="link" value={item.link} onChange={updateItem} />
<br/><br/>
<input type="text" name="title" id="title" value={item.title} onChange={updateItem} />
<br/><br/>
<textarea name="desc" id="desc" value={item.desc} onChange={updateItem} />
<input type="button" value="click" onClick={aaa} />
</form>
);
}
export default Test;
CodePudding user response:
I found some problem in your code and by fixing that I think your issue will be resolved :
First, you cannot assign value to state directly so change this part :
const updateItem = (e) => {
item[e.target.id] = e.target.value;
setItem(item);
}
to this part :
const updateItem = (e) => {
setItem({...item,[e.target.id]:e.target.value});
}
Second, name of scope in aaa function is the same as state, that might cause error, so change name of it or assign value directly, like this :
const aaa = () => {
setItem({
link : 'testlink',
title : 'testtitle',
desc : 'testdesc'
});
}