javascript - 使 RBSheet 可作为 React-Native 小部件重复使用

标签 javascript react-native package bottom-sheet

我正在使用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/

相关文章:

javascript - 将 JavaScript 对象函数关联到 HTML 元素

与 react native 相关的UNMET PEER DEPENDENCY的npm问题

react-native - Picker onValueChange 不是在每次选择时都被调用

javascript - listRef.listAll() 函数未定义(react-native-firebase)

installation - 手动安装 Octave 包

javascript - 有没有办法查看(匿名)函数内部?

javascript - 如何在 JavaScript 中处理任意数量的参数时柯里化(Currying)?

javascript - 在服务器上调用 Collection.insert 时为 "Meteor code must always run within a Fiber"

java - 如何通过 Package.getPackage(...) 访问包?

database - 编译包体时出现 PLS-00324 错误