gpt4 book ai didi

javascript - 如何更改来自 React 中 props 的输入值?

转载 作者:行者123 更新时间:2023-11-28 16:51:10 25 4
gpt4 key购买 nike

我想在 React 中创建多个动态输入,我的代码如下所示:

import React, { useState } from "react";
import "./styles.css";

const style = {
display: "flex",
justifyContent: "center",
alignItems: "center",
flexWrap: "wrap"
};

const dataarray = [
{ name: "name1", value: 12 },
{ name: "name2", value: 20 },
{ name: "name3", value: 30 },
{ name: "name4", value: 40 },
{ name: "name5", value: 50 }
];

export default function App() {
const [data, setData] = useState(dataarray);

const onChange = e => {
setData({ [e.target.name]: e.target.value });
};

const onClick = e => {
e.preventDefault();

console.log("data ", data);
};

return (
<div className="App" style={style}>
{dataarray.map((item, index) => {
return (
<div key={index} style={{ display: "flex", flexDirection: "column" }}>
<input
type="text"
style={{ marginTop: "100px" }}
value={
data.find(localItem => localItem.value === item.value).value
}
name={item.name}
onChange={onChange}
/>
</div>
);
})}
<button onClick={onClick}>Submit</button>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

默认状态来自 probs,但是当我更改任何输入的值时,它就会中断。这是沙盒演示 demo

有什么方法可以改变输入值吗?感谢任何帮助

最佳答案

从您提供的沙箱中,第 27 行:

只需更改:

setData({inputs});

至:

setData(inputs);

这使得状态从

{
inputs: [
// the inputs...
]
}

至:

[
// the inputs...
]

或者只是不要使用数组作为状态

这将使一切变得更加容易:

import React, { useState } from "react";
import "./styles.css";

const style = {
display: "flex",
justifyContent: "center",
alignItems: "center",
flexWrap: "wrap"
};

const initialData = {
"name1": 12,
"name2": 20,
"name3": 30,
"name4": 40,
"name5": 5
};

export default function App() {
const [data, setData] = useState(initialData);

const onChange = e => {
setData({...data, [e.target.name]: e.target.value });
};

const onClick = e => {
e.preventDefault();

console.log("data ", data);
};

return (
<div className="App" style={style}>
{Object.keys(data).map((key, index) => {
return (
<div key={index} style={{ display: "flex", flexDirection: "column" }}>
<input
type="text"
style={{ marginTop: "100px" }}
value={data[key]}
name={key}
onChange={onChange}
/>
</div>
);
})}
<button onClick={onClick}>Submit</button>
</div>
);
}

关于javascript - 如何更改来自 React 中 props 的输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59940915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com