5
我想用另一個項目替換我的數組中的單個項目,我有一個佔位符與其上的數字位置,當我點擊添加第一個項目應該進入第一個位置,第二項進入第二位,依此類推。React在數組中替換項目
目前它會在點擊時添加所有位置的項目,這不是我想要的行爲。
如果我刪除了數位佔位符,我可以讓他們進入在正確的位置排列,但我無法得到它與佔位符的工作。
如何在單擊時替換數組中的數字位置來獲取產品項目?
https://codesandbox.io/s/6z48qx8vmz
Hello.js
import React from 'react';
import update from 'immutability-helper'
import styled from 'styled-components'
import Product from './Product'
const NumberWrap = styled.div`
display: flex;
flex-wrap:wrap
border: 1px solid #ccc;
flex-direction: row;
`
const Numbers = styled.div`
display:flex;
background: #fafafa;
color: #808080;
font-size: 32px;
flex: 0 0 20%;
min-height: 200px;
justify-content: center;
align-items:center;
border-right: 1px solid #ccc;
`
const CardWrap = styled.div`
display:flex;
flex-wrap: wrap;
flex-direction: row;
margin-top: 20px;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
placeholder: [1,2,3,4,5],
data: [
{ id: 1, header: 'Item 1'},
{ id: 2, header: 'Item 2'},
{ id: 3, header: 'Item 3'},
{ id: 4, header: 'Item 4'}
],
addedItems: [],
}
this.handleAdd.bind(this)
this.handleRemove.bind(this)
}
handleAdd(id) {
this.setState({
addedItems: update(this.state.addedItems, {
$push: [
id,
],
})
})
}
handleRemove(index) {
this.setState({
addedItems: update(this.state.addedItems, {
$splice: [
[index, 1]
],
})
})
}
render() {
return(
<div>
<NumberWrap>
{
this.state.placeholder.map(item =>
<Numbers>{item}
{
this.state.data.filter(item =>
this.state.addedItems.indexOf(item.id) !== -1).slice(0, 5).map(item =>
<Product {...item} remove={this.handleRemove} />
)
}
</Numbers>
)}
</NumberWrap>
<CardWrap>
{
this.state.data.map(item =>
<Product {...item} add={()=>this.handleAdd(item.id)} />
)}
</CardWrap>
</div>
)
}
}
Product.js
import React from "react";
import styled from "styled-components";
const Card = styled.div`
flex: 0 0 20%;
border: 1px solid #ccc;
`;
const Header = styled.div`
padding: 20px;
`;
const AddBtn = styled.button`
width:100%;
height: 45px;
`;
const Product = props => {
const { add, id, header, remove } = props;
return (
<Card>
<Header key={id}>
{header}
</Header>
<AddBtn onClick={add}>Add</AddBtn>
<AddBtn onClick={remove}>Remove</AddBtn>
</Card>
);
};
export default Product;
感謝,這是我後我,但我也希望能夠刪除號碼時,該產品被添加所以只顯示產品 –
只是比較你有多少添加的項目有佔位指數和基於要麼顯示數字,要麼顯示數字 –