gpt4 book ai didi

javascript - React JS 映射对象名称的问题

转载 作者:行者123 更新时间:2023-12-02 22:37:22 25 4
gpt4 key购买 nike

我尝试映射对象属性名称和值以生成输入片段。虽然映射适用于初始输入值,但无法迭代属性名称来调用其状态 Hook 。

我尝试了很多方法,例如; Object.entries(hurdleRates).map(([key, value]) => {...
})`
或者 Object.keys(hurdleRates).map(function(key) {...
})`

请帮忙!谢谢!

import React, { useState } from "react";

const RateSettings = () => {

const [hurdleRates, sethurdleRates] = useState({
bcLombard: 0.1,
bcOtherSecured: 0.2,
bcUnsecured: 0.3
});

return (
<div>
{Object.keys(hurdleRates).map(function(key) {
return (
<input
value={hurdleRates[key]}
onChange={e => sethurdleRates({ key: e.target.value })}
></input>
);
})}
</div>
);
};

export default RateSettings;

作为结果,我期望三个输入标签生成三个输入框。在代码中,每个代码应类似于以下第一个代码;

<input value=0.1 onChange{e => sethurdleRates({bcLombard : e.target.value})}> </input>

最佳答案

使用Object.entries(),但使用key作为要使用计算属性名称分配的状态的属性{ ...状态,[key]:e.target.value }

注意:如果您不想使用其他输入,您还应该传播状态 - { ...state, [key]: e.target.value }

const { useState } = React;

const RateSettings = () => {
const [hurdleRates, sethurdleRates] = useState({
bcLombard: 0.1,
bcOtherSecured: 0.2,
bcUnsecured: 0.3
});

return (
<div>
{Object.entries(hurdleRates).map(([key, value]) => {
return (
<input
key={key}
value={value}
type="number"
onChange={e => sethurdleRates({ ...hurdleRates, [key]: +e.target.value })}
></input>
);
})}
</div>
);
};

ReactDOM.render(
<RateSettings />,
root
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

关于javascript - React JS 映射对象名称的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701520/

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