首页 > 解决方案 > 如何使用 ImagePicker 在轮播中选择图像?

问题描述

我创建了一个轮播,其中图像动态存储。我想选择多个图像并捕获选定的图像。现在,无论我选择的哪个图像想要显示在另一个页面上,我都使用了 ImagePicker。显示多个图像,因为我在地图内使用地图。我尝试了很多,但我无法解决这个问题。请帮忙。这是我的代码和输出。

import React from "react";
import Carousel, { Dots } from '@brainhubeu/react-carousel';
import '@brainhubeu/react-carousel/lib/style.css';
import ImagePicker from 'react-image-picker';

class CropSelection extends React.Component {

constructor(props) {
super(props)
this.state = {
  imgslides: [],
  img: []
}
this.onPick = this.onPick.bind(this);
}
componentDidMount = () => {

fetch('http://localhost/fruit_api/carousel_api.php')

.then((response) => response.json())

.then(data => {
  console.log(data)

  let slides = data.data.map((pic, key) => {
    return(
      <div className="images-data">

        {/* <ImagePicker 
            images={data.data.map((image, i) => ({src: image.img, value: i}))}
            onPick={this.onPickImages}
            multiple
        /> */}
        <img src = {pic.img} alt="" /> 
      </div>
    )
  })
  this.setState({
    imgslides: slides
  })
  // console.log("state", this.state.slides);
})
.then(function(response){
  console.log(response)
})

.catch(function(response){
  console.error(response)
});

}
onPick = (image) => {
 this.setState({image})
}
render() {

return (
  <div className="caurosel-div">

   <Carousel
    arrows
    slidesPerScroll={1}
    slidesPerPage={5}
    // value={this.state.value}
    slides = {this.state.imgslides} 
    onChange={this.onchange}
    >
      {/* <ImagePicker
        images = {this.state.imgslides}
        multiple
      /> */}
    {/* <button type="button" onClick={() => console.log(this.state.img)}>OK</button> */}

     </Carousel> 

  );
 }
}


export default CropSelection;

输出

标签: reactjs

解决方案


这里的问题是,当您尝试在 Carousel 中渲染 ImagePicker 时,由于组件的预期和渲染方式都不同,您看不到渲染发生。Carousel 组件需要,但您的 ImagePicker 以 .

如果您尝试使用 ImagePicker 只是为了选择图像,则可以直接使用 Carousel 本身和很少的自定义 css 来完成。从您的图像列表中,您可以在轮播中渲染图像,为每个 img 分配一个 onclick 以获取所选图像,并更改类名以显示类似于 Image Picker 的所选图像效果。

这是实现上述内容的工作示例 - https://react-n57tkq.stackblitz.io/

代码 - https://stackblitz.com/edit/react-n57tkq?file=index.js

在上面的示例中,正在选择单个图像。如果您想将多个图像作为选择过程的一部分,则将其作为一组选定图像。您可以使用此数组在其他组件中显示选定的图像。

希望这可以帮助!

D


推荐阅读