【发布时间】:2021-05-28 09:27:09
【问题描述】:
我正在尝试在 reactjs 中编写一个函数,其中输入值将在给定数组 onclick 特定索引添加按钮中按顺序更新。 它是我到目前为止所做的沙盒链接: https://codesandbox.io/s/sidename-8k2z3 这是 json 形式的状态值:
this.state ={
locationSiteList:[ {
"sideName": 'Ceiling',
"length": "",
},
{
"sideName": 'Floor',
"length": "",
},
{
"sideName": 'East wall',
"length": "",
}
],
};
我想要的是,如果单击第一个索引上的添加按钮,则 sideName 将自动更改为 Ceiling1 并将添加另一个名为天花板 2 的数组。再次,如果我单击楼层添加按钮,则为楼层索引更改为 floor1,floor2。预期结果将如下所示:
locationSiteList:[ {
"sideName": 'Ceiling1',
"length": "",
},
{
"sideName": 'Ceiling2',
"length": "",
},
{
"sideName": 'Floor1',
"length": "",
},
{
"sideName": 'Floor2',
"length": "",
},
{
"sideName": 'East wall',
"length": "",
}
],
这是在渲染我正在映射:
<Grid item xs={12}>
{
this.state.locationSiteList.map((dev, key) =>
<Grid container style={{marginTop:'8px'}}>
<Grid item xs={3} style={{}}>
<input disabled style={{width:'100%'}}
type="text" value={dev.sideName} />
</Grid>
<Grid item xs={1} style={{paddingLeft:'8px'}}>
<input disabled style={{width:'100%'}}
type="text" />
</Grid>
<button type="button" fullWidth="true" variant="contained"
onClick={() => { this.insertSides()}}>
Add
</button>
</Grid>
)}
</Grid>
这是我的添加功能:
insertSides = () => {
console.log('rawInsert....');
const locationSiteList = [...this.state.locationSiteList];
if (locationSiteList.length < 1) {
var a = 1
} else {
var a = locationSiteList.length + 1
}
locationSiteList.push({
'sideName': a,
});
this.setState({locationSiteList: locationSiteList});
};
我怎样才能让它工作?
【问题讨论】:
标签: javascript arrays json reactjs