我正在尝试创建一个具有可变数量输入的图像库。我已经成功创建了一个添加按钮,它将向状态中的数组添加新元素。但是,当我单击按钮从数组中删除一个元素时,它将删除除第一个元素以外的所有元素。有人可以帮我弄清楚我要去哪里哪里吗?
我在父组件中的初始化/添加/删除逻辑:
const newImage = {
fileName: 'placeholder.png',
description: '',
}
const [galleryImages, setGalleryImages] = useState([newImage])
const addNewImage = () => {
setGalleryImages(galleryImages.concat(newImage))
}
const removeImage = (index) => {
setGalleryImages(galleryImages.splice(index, 1))
}
我的图片库组件:
const ImageGallery = ({galleryImages, setGalleryImages, addNewImage, removeImage}) => {
console.log('gallery images:', galleryImages)
return(
galleryImages.map((image, index) => {
const fileId = 'image' + (index + 1) + 'File'
const descriptionId = 'image' + (index + 1) + 'Description'
return(
<Card key={index} style={{marginTop: '10px'}}>
<Card.Body>
<div style={{position: 'absolute', top:'5px', right:'5px'}}>
<IconButton aria-label="remove" color="secondary" onClick={() => removeImage(index)}>
<CancelIcon />
</IconButton>
</div>
<Card.Title>Image {index+1}</Card.Title>
<Form.Group>
<Form.File id={fileId} />
<Form.Label>Image Description</Form.Label>
<Form.Control id={descriptionId} type="text" placeholder="Image description..."/>
</Form.Group>
</Card.Body>
{ index === (galleryImages.length - 1) &&
<div style={{left: '0px', right:'0px', flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', bottom: '-30px', position: 'absolute'}}>
<IconButton aria-label="add another image" onClick={() => addNewImage()}>
<AddCircleIcon style={{color: 'green', fontSize: 40, backgroundColor: 'white', borderRadius: '50%'}}/>
</IconButton>
</div>
}
</Card>
)
})
)
}
答案 0 :(得分:2)
Splice直接更改数组,这通常在React中被拒登。
虽然推荐的方法是使用filter方法删除,但是如果您要使用拼接,则可以按照这种方式进行操作-
const removeImage = (index) => {
//create a new array here with the spread operator of the original array.
//Without this, react won't recognize the change and the child component won't be re-rendered!
const galleryImagesData = [...galleryImages];
galleryImagesData.splice(index, 1)
setGalleryImages(galleryImagesData)
}