我正在使用RBSheet Package用于显示我的项目中的 Bottom Sheet 。我已经从文档中理解了如何使用它的概念。 有没有办法让 Bottom Sheet 像小部件一样可重复使用?我尝试过这样做:
BottomSheetComponent.js
const BottomSheet = ({ message, buttonText }) => {
// to open this sheet as soon as someone call this Component
this.RBSheet.open();
return(
<RBSheet ref={ ref => { this.RBSheet = ref; }}
customStyles={{mask: { backgroundColor: COLORS.dark }, container: { elevation: 100 }}}>
<View style={styles.messageContainer}>
{/* Add more data later */}
</View>
</RBSheet>
);
}
export default BottomSheet;
MainComponent.js
const MainComponent = () => {
const bottomSheet = () => {
// Trying to call the bottom sheet here
<BottomSheet />
}
return(
<View>
<Button onPress={() => bottomSheet()} title="Bottom Sheet" />
</View>
);
}
export default MainComponent;
我未能获得 Bottom Sheet 。我刚刚开始研究 React Native。我不想采用包文档中解释的通用方法,从头开始在两个不同的页面中制作相同的 Bottom Sheet 并不是一个好的做法。
最佳答案
经过大量研究,我终于弄清楚我做错了什么。
- 我将它用于
类组件
,尽管我使用的是功能组件
- 缺少引用,
Metro Build Runner
给我带来了错误。
解决方案
解决问题的方法:
- 我需要创建自己的引用
- 将其传递给包的
ref
属性
MainComponent.js
import React, { useRef } from 'react';
const MainComponent = () => {
// To be used for the reference for the bottom sheet
const sheetRef = useRef();
const bottomSheet = () => {
// Here how you open the bottom sheet right
sheetRef.current.open();
}
return(
<View>
<Button onPress={() => bottomSheet()} title="Bottom Sheet" />
{/* Passing the sheet ref for the binding */}
<BottomSheet sheetRef={sheetRef} />
</View>
);
}
export default MainComponent;
BottomSheet.js
const BottomSheet = ({ sheetRef }) => {
return(
{/* This is the place to make it work */}
<RBSheet ref={sheetRef}
customStyles={{mask: { backgroundColor: COLORS.dark }, container: { elevation: 100 }}}>
<View style={styles.messageContainer}>
{/* Add more data later */}
</View>
</RBSheet>
);
}
export default BottomSheet;
关于javascript - 使 RBSheet 可作为 React-Native 小部件重复使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65034545/