1

我尝试使用 react-native-raw-bottom-sheet 作为可重用组件。我创建了一个父组件,问题是当我尝试给出值时出现此错误。

 TypeError: undefined is not an object (evaluating 'refRBSheet.current.open')

父组件

import React from 'react';
import RBSheet from 'react-native-raw-bottom-sheet';

const CustomActionSheet = (props) => {
  const { ref, Content, height } = { ...props };
  return (
    <RBSheet
      height={height}
      ref={ref}
      closeOnDragDown={true}
      closeOnPressMask={true}
      customStyles={{
        wrapper: {
          backgroundColor: 'transparent',
        },
        draggableIcon: {
          backgroundColor: '#000',
        },
      }}
    >
      {Content}
    </RBSheet>
  );
};

export default CustomActionSheet;

子组件

<View style={styles.chsDlvrBtn}>
          <Button title="Choose Delivery" onPress={() => refRBSheet.current.open()} />
        </View>
        <CustomActionSheet
          ref={refRBSheet}
          Content={
            <View style={styles.view}>
              {MONTH_OF_YEAR.map((val) => {
                return (
                  <Chip mode="outlined" onPress={() => {}} style={styles.chp}>
                    {val}
                  </Chip>
                );
              })}
            </View>
          }
        />

参考挂钩

const refRBSheet = useRef()

这里出了什么问题。谢谢,提前!!!

4

1 回答 1

1

我只知道如何用功能组件做到这一点,但这样做......

  1. 将 RBSheet 或任何 ref'd 表放在子组件中

  2. 将子组件导入父组件(将带有上滑片的组件导入主组件

  3. 使用类似的东西在父组件中创建一个 refthis.sheetRef = React.createRef();

  4. 将该 ref 作为道具传递给您的 RBSheet 子组件(RBSheet 应该在子组件中-而不是父组件中-您实际上是在导入带有 RBSheet 的辅助组件)-应该类似于<MyChildComponent {...otherProps} sheetRef={this.sheetRef} />

  5. 要在父组件中打开,请在子组件中执行类似的操作this.sheetRef.current.open();,例如sheetRef.current.close();

  6. 子组件中的 RBSheet 应类似于...

    import RBSheet from 'react-native-raw-bottom-sheet'
    
    const MyChildComponent = ({ sheetRef }) => {
    useEffect(() => {
        sheetRef.current.close();
    }, [])
    return(
            <RBSheet
                ref={sheetRef} 
                closeOnDragDown={true}
                height={height * 0.90}
                openDuration={250}
                customStyles={{
                    container: {
                        borderTopLeftRadius: 40,
                        borderTopRightRadius: 40
                    },
                    draggableIcon: {
                        backgroundColor: "grey",
                        width: 250
                    }
                }}
                > 
            </RBSheet>
        );
    };
    
    
  7. 父组件应该看起来像......


class MyParentComponent extends Component {
constructor (props) {
super(props);
 this.sheetRef = React.createRef();
}
componentDidMount () {
   this.sheetRef.current.open();
}
render () {
  return (
     <Fragment>
          <MyChildComponent {...otherProps} sheetRef={this.sheetRef} />
     </Fragment>
  );
 }
}

于 2021-05-31T00:10:40.527 回答