我正在尝试更改输入值,但它没有更改。
一旦改变,数值不会改变
我可以知道的原因吗
有什么建议吗?
请参阅下面的片段
// snippets
import React, {useState} from 'react';
const StackOverFlow = () => {
let rowData = [
{ header: "first" },
{ header: "second" },
{ header: "third" }
];
const [name, setName] = useState({ fn: "test" });
const [data, setData] = useState(rowData);
const getOnchange = (e) => {
console.log('--e--',e.target.value)
setName({ ...name, fn: e.target.value })
}
let updateValue = () => {
setData([
...data,
{
header: (
<input
type="text"
value={name.fn}
onChange={getOnchange}
/>
)
}
]);
};
return (
<div>
{data.map(val => (
<h6>{val.header}</h6>
))}
<button onClick={updateValue}> Click </button>
</div>
);
};
export default StackOverFlow
该值不会更改,因为一旦您将JSX设置为状态data
,它将在调用setData
时取该值,并且在执行getOnChange
时不会更改,
import React, { useState } from "react";
const StackOverFlow = () => {
let rowData = [
{ header: "first" },
{ header: "second" },
{ header: "third" }
];
const [name, setName] = useState({ fn: "test" });
const [data, setData] = useState(rowData);
const getOnchange = e => {
console.log("--e--", e.target.value);
setName({ ...name, fn: e.target.value });
};
let updateValue = () => {
setData([
...data,
{
header: name.fn
}
]);
setName({ ...name, fn: e.target.value });
};
return (
<div>
{data.map(val => (
<h6 key={val.header}>{val.header}</h6>
))}
<input type="text" value={name.fn} onChange={getOnchange} />
<button onClick={updateValue}> Click </button>
</div>
);
};
export default StackOverFlow;
这是一个替代方法,你正在努力实现什么。