我想不出很简单的东西:-(
我正在用React构建一个图像滑块,这个想法是:
data.js
文件,其中包含图像文件路径。 import React from 'react';
import pics from './data'; //-->array with paths to images.
function App() {
let path =`./wallpapers/${pics[0]}`
console.log(path)
return (
<div className="App">
<img className='image' src={path} alt='dont know how will fix this, we dont have a way to generate alt content'/>
<div className='panel'>
<button>Left</button>
<button>Right</button>
</div>
</div>
);
}
export default App;
现在我很困惑,因为这是javascript图像不会那样加载。有什么方法可以实现这一目标,还是我应该研究的任何技术?
答案 0 :(得分:0)
您将需要某种“当前”图像设置。单击按钮将触发该值向上或向下。默认将其设置为0。此代码无法按原样工作,但概念如下:
import React, { useState } from 'react'
import wallpapers from './wallpapers'
function App() {
[ currentImage, setCurrentImage ] = useState(0)
const path =`./wallpapers/${wallpapers[currentImage]}`
return (
<div className="App">
<img className='image' src={path} alt='dont know how will fix this, we dont have a way to generate alt content'/>
<div className='panel'>
<button onClick={() => setCurrentImage(currentImage - 1)}>Left</button>
<button onClick={() => setCurrentImage(currentImage + 1)}>Right</button>
</div>
</div>
);
}
在单独的文件中,您可以导入所有图像
// wallpapers/index.js
import Wall1 from './wallpapers/1.png';
import Wall2 from './wallpapers/2.png';
import Wall3 from './wallpapers/3.png';
import Wall4 from './wallpapers/4.png';
import Wall5 from './wallpapers/5.png';
import Wall6 from './wallpapers/6.png';
export default [
Wall1,
Wall2,
Wall3,
Wall4,
Wall5,
Wall6
]