我正在制作一个React作品集,其中一个组件将是一个图片库(不用说我是React的新手,我想知道,否则我不会问这个问题)。为此,我将使用一个包(react-image-gallery),该包可让我自定义几个项目。我已经安装了,并且运行良好,但是我需要对其进行自定义-隐藏缩略图以及“播放”和“全屏”按钮。
根据文档,可以通过状态来执行此操作。问题是我无法这样做,因为该应用程序的导航使用了路由器,尽管我努力了,但无法使状态传递到放置在路由器上的组件中。这是不起作用的主要组件(等效于App)的代码:
import "./styles.css";
import {
HashRouter,
NavLink,
Route
} from "react-router-dom";
import React, { Component } from "react";
import Development from "./Development";
import Home from "./Home";
import Intro from "./Intro";
import Media from "./Media";
import StudyCase from './StudyCase';
import Stuff from "./Stuff";
class Main extends Component {
constructor() {
super();
this.state = {
showThumbnails: false
};
}
render() {
return (
<HashRouter>
<div>
<ul className='top-menu'>
<li>
<NavLink className='navs hvr-pulse' to='/'>
Home
</NavLink>
</li>
<li>
<NavLink className='navs hvr-pulse' to='/dev'>
Development
</NavLink>
</li>
<li>
<NavLink className='navs hvr-pulse' to='/media'>
Media
</NavLink>
</li>
<li>
<NavLink className='navs' to='/study-case'>
Study Case
</NavLink>
</li>
</ul>
<span className='bottom-slider'></span>
<div className='content'>
<Route exact path='/' component={Intro} />
<Route path='/dev' component={Development} />
<Route path='/media' component={Media} />
<Route path='/study-case' render={props => (<StudyCase {...this.state} showThumbnails={this.state.showThumbnails}/>)}/>
</div>
</div>
</HashRouter>
);
}
}
export default Main;
一些同事可以指出我对我的错误吗?预先感谢您的可用性。
答案 0 :(得分:0)
几个小时后,我找到了解决方案,这是非常基本的,所以新手可以找到答案。碰巧<StudyCase/>
组件本身就有一个组件,并且状态应该存在于此。我以前使用的Gallery包的原理导致我出错,在该包中,必须在路由器的同一页面中处理状态。这是<StudyCase/>
组件的代码,具有工作状态(如果有人有时需要的话):
import ImageGallery from 'react-image-gallery';
import React from 'react';
class StudyCase extends React.Component {
constructor() {
super();
this.state = {
showThumbnails: false,
showPlayButton: false,
showFullscreenButton: false,
showGalleryFullscreenButton: false,
};
}
render() {
return (
<ImageGallery
items={images}
showThumbnails={this.state.showThumbnails}
showPlayButton={this.state.showPlayButton && this.state.showGalleryPlayButton}
showFullscreenButton={
this.state.showFullscreenButton && this.state.showGalleryFullscreenButton
}
/>
// <ImageGallery
// items={images}
// showThumbnails={this.state.showThumbnails} />;
);
}
}
const images = [
{
original: 'https://picsum.photos/id/1018/1000/600/',
thumbnail: 'https://picsum.photos/id/1018/250/150/',
},
{
original: 'https://picsum.photos/id/1015/1000/600/',
thumbnail: 'https://picsum.photos/id/1015/250/150/',
},
{
original: 'https://picsum.photos/id/1019/1000/600/',
thumbnail: 'https://picsum.photos/id/1019/250/150/',
},
];
export default StudyCase;