提问人:Martinocom 提问时间:11/13/2023 更新时间:11/13/2023 访问量:16
App Intro Slider 在页面上具有可检查的输入 - 从父级调用操作,向父级发送事件
App Intro Slider with checkable inputs on pages - calling actions from parent, sending events to childrens
问:
我从两周开始就一直在为这个问题而苦苦挣扎,我在这里寻求帮助。
我无法弄清楚如何在 ReactNative 中制作水平页面滑块,以避免无用地重新渲染我在 FlatList 中的所有页面。要求是:
- 幻灯片是唯一水平滚动的东西,为此......
- ...按钮不在儿童内部
- 孩子们必须实现自己的方法,并且:每个孩子都会有这些方法,但他们在如何返回真/假方面可能会有所不同
isEverythingOk
onAction
- 这些方法必须可从父级调用
它类似于 react-native-app-intro-slider,但每张幻灯片都会有一些输入,这些输入必须在下一步之前进行验证,最终有一些额外的操作将由一个额外的按钮启用。
解释这一点的最简单方法是以下代码:
const SLIDES = [
{component: Intro, extraAction: false},
{component: SetName, extraAction: false},
{component: SetBudget, extraAction: true}}
]
const MyComponent = () => {
const listRef = useRef(null);
const [currentSlide, setCurrentSlide] = useState(0);
useEffect(() => {
listRef.current?.goToIndex({animated: true, index: currentIndex)};
}, [currentSlide])
const onPrev () => {
setCurrentSlide(currentSlide - 1);
}
const onNext () => {
// Problem 1 => I have no reference to currentSlide component
if (currentSlide.isEverythingOk()) {
setCurrentSlide(currentSlide + 1);
}
}
const onAction () => {
// Problem 2 => I have no reference to currentSlide component
currentSlide.onAction();
}
// Problem 3 => How to pass this to every children?
const onActionCompleted = () => {
onNext();
}
<View>
<FlatList ref={listRef} data={SLIDES} renderItem={(item) => item.component} />
<ButtonContainer>
<Button onPress={onNext} />
{SLIDES[currentSlide].extraAction ? <Button onPress={onAction} /> : null }
<Button onPress={onPrevious} />
</ButtonContainer>
</View>
}
其中一个组件的示例可以是:
const SetName = () => {
const [isOk, setIsOk] = useState(false);
// Problem 1 - I should call this from parent
const isEverythingOk = () => {
return isOk;
}
// Problem 2 - I should call this from parent
const onAction = () => {
openDialog();
// Problem 3 => I need the "onActionCompleted"!
}
//... an so on, every Child component will surely have those two methods
}
我用 // 问题 X
注释标记了问题。
我采用一种经典的编程方式,我会有一个实现 with 和 的组件,我会从父项那里假设每个子项都属于该类型,我可以去检查当前项目并调用该方法。interface
onAction
isEverythingOk
但在 React 中不是。
我无法(或不知道如何)在更改时更新当前引用,如果我更新父项中的某些内容,每个组件都会重新渲染,当我有 15 个滑动页面时会造成巨大的问题。我可以在这些组合上使用备忘录,但它是无用的,因为在每次更改时,onActionCompleted 也会更改,因为 onNext 会更改。currentSlide
我考虑过 EventEmitters、refs 和所有可能的解决方案,但最终总有一些东西无法使其工作(无用的重新渲染、不工作的事件、未更新的 refs......
只是,请,帮忙。
如果我们能找到一个优雅的解决方案,我将为每个人提供代码,并为它发布一个 NPM 包。
答: 暂无答案
评论