简体   繁体   English

在同一个 React 组件 React 的两个特定实例之间共享 State

[英]Share State between two specific instances of the same react component React

Before y'all say global state(redux), I'd like to say one thing.在你们说全局状态(redux)之前,我想说一件事。 I'm mapping through an array I fetched from my API.我正在映射从我的 API 获取的数组。 I receive images and map over them and render my Slider component.我收到图像和 map 并渲染我的Slider组件。 Every 2 sliders must share the same state.每 2 个滑块必须共享相同的 state。 So, then if i move to the next slide in the first slider, then the second slider must also go to the next slide(but not any other slides).所以,如果我移动到第一张 slider 中的下一张幻灯片,那么第二张 slider 也必须 go 到下一张幻灯片(但不是任何其他幻灯片)。 If I move to the next slide in the 5th slider, the 6th must also move to the next slide... so on.如果我移到第 5 张 slider 中的下一张幻灯片,第 6 张也必须移到下一张幻灯片……以此类推。

Component where I map over slides:我 map 滑过的组件:

<div className='image-grid'>
                {screenshots.map((imagesByResolution, resIdx, screenshotResArr) => {
                    return imagesByResolution.map((img, scriptIdx, screenshotScriptsArr) => {
                        return <Slider slides={formattedSlides} />;
                    });
                })}
            </div>

Slider : Slider

import Button from '@material-ui/core/Button';
import MobileStepper from '@material-ui/core/MobileStepper';
import { useTheme } from '@material-ui/core/styles';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import React from 'react';
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import { encodeImage } from '../services/images';
import useStyles from '../styles/slider';

const AutoPlaySwipeableViews = autoPlay(SwipeableViews);

export interface ISlide {
    title: string;
    img: ArrayBuffer;
}

interface Props {
    slides: ISlide[];
}

export default function Slider(props: Props) {
    console.log(props);

    const { slides } = props;
    const classes = useStyles();
    const theme = useTheme();

    const [activeSlide, setActiveSlide] = React.useState(0);
    const maxSlides = slides.length;

    const handleNext = () => {
        setActiveSlide((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveSlide((prevActiveStep) => prevActiveStep - 1);
    };

    const handleSlideChange = (step: number) => {
        setActiveSlide(step);
    };

    return (
        <div className={classes.root}>
            <div className={classes.header}>
                <h4 className={classes.title}>{slides[activeSlide].title}</h4>
            </div>

            <AutoPlaySwipeableViews
                axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
                index={activeSlide}
                onChangeIndex={handleSlideChange}
                enableMouseEvents
            >
                {slides.map((slide, index) => (
                    <div key={index}>
                        {Math.abs(activeSlide - index) <= 2 ? (
                            <img className={classes.img} src={encodeImage(slide.img, 'image/png')} alt={slide.title} />
                        ) : null}
                    </div>
                ))}
            </AutoPlaySwipeableViews>

            <MobileStepper
                steps={maxSlides}
                position='static'
                variant='text'
                activeStep={activeSlide}
                nextButton={
                    <Button size='small' onClick={handleNext} disabled={activeSlide === maxSlides - 1}>
                        Next
                        {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
                    </Button>
                }
                backButton={
                    <Button size='small' onClick={handleBack} disabled={activeSlide === 0}>
                        {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
                        Back
                    </Button>
                }
            />
        </div>
    );
}

If this is not possible using either some global state management library or plain ol' react state, what is the other alternative?如果使用某些全局 state 管理库或普通的反应 state 都无法做到这一点,那么其他选择是什么? Thanks in advance!提前致谢!

Pass a unique key prop to each instance of your component.将唯一的key prop 传递给组件的每个实例。

Credits: https://stackoverflow.com/a/65654818/9990676学分: https://stackoverflow.com/a/65654818/9990676

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM