【问题标题】:Pick image form React Carousel and push it into a new variable从 React Carousel 中选择图像并将其推送到新变量中
【发布时间】:2021-01-02 14:24:36
【问题描述】:

例如,我有一个带有 4 张图像的 React Carousel。

import React from 'react'
import { FacebookShareButton } from "react-share";

import img1 from './images/kitten/200.jpg'
import img2 from './images/kitten/201.jpg'
import img3 from './images/kitten/202.jpg'
import img4 from './images/kitten/203.jpg'

const imageList = [img1, img2, img3, img4]

 class App extends Component {
   constructor(props) {
     super(props)
     this.selected = "";
 }

 render() {
   return (
     <div>
      <Carousel>
         {imageList.map((each) => (
         <img src{each} />
         ))}
      </Carousel>
     </div>
    )
  }
}
export default App;

我想从滑块中选择一张图片

并将其推送到上面定义的名为this.selected的新变量中

谢谢

【问题讨论】:

  • 我建议使用state
  • @Score-6 感谢您的建议,这是一个好主意,但是例如如何将图像从 Carousel 获取到状态?如果你能分享一个例子,那将非常有帮助
  • this.setState()
  • 我应该把它放在哪里?在 里面还是在 render 和 setState 外面创建箭头函数?
  • 在下面查看我的答案。

标签: javascript reactjs frontend web-frontend


【解决方案1】:

根据您的建议,这是您想要的吗?

import React from 'react'
import { FacebookShareButton } from "react-share";

import img1 from './images/kitten/200.jpg'
import img2 from './images/kitten/201.jpg'
import img3 from './images/kitten/202.jpg'
import img4 from './images/kitten/203.jpg'

const imageList = [img1, img2, img3, img4]
class App extends Component {
 constructor(props) {
     super(props)
     this.state = {selected: ""};
 }
 pickFromCarousel(image) {
     this.setState({selected: image});
 }

 render() {
   return (
     <div>
      <Carousel>
         {imageList.map((each) => (
         <img onClick={() => this.pickFromCarousel(each)} src={each} />
         ))}
      </Carousel>
     </div>
    )
  }
}
export default App;

使用state

我正在做的是在构造函数中将selected 添加到state,当然,首先将其设置为null。我们添加了一个名为pickFromCarousel 的函数,它表示将selected 设置为请求的图像。然后,在我们的render 函数中,我们使用pickFromCarousel 作为点击图像时的函数,通过使用箭头函数。其余代码与您的几乎相同。

【讨论】:

  • codesandbox.io/s/agitated-sara-rln7f?file=/src/App.js 有错误请检查附件,请问为什么函数名称是 addToCarousel 应该从轮播中选择,因为这正是我想要实现的目标
  • @Dev01 因为您的帖子令人困惑。
  • 我已经在标题中说过没关系?你检查链接了吗?
  • 是的。我当然做了。我正在努力解决问题。
  • 好的,我很感激
猜你喜欢
  • 2013-07-11
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2021-01-12
相关资源
最近更新 更多