【问题标题】:Unable to call Method from another class in React Native无法从 React Native 中的另一个类调用方法
【发布时间】:2019-01-28 14:56:37
【问题描述】:

我有以下 Snack 设置(请使用 Android 版本):

https://snack.expo.io/@sj458147/stackoverflow-unable-to-call-method

  1. 当点击 Go to step 2 - I get undefined is not an object 时,视图应通过调用方法滚动 - moveToPage

  2. 如果用户要滑动模态视图,它将移至下一个视图。如何停止这种交互(视图应该只在用户单击按钮而不是滑动时滚动)。

  3. Expo 显示 this.refs 已弃用,我将如何更新此代码?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您需要在构造函数中使用 React.createRef()。并在您的组件中使用此参考。在 go() 函数中,要实现 moveToPage(2) 您需要使用当前引用,如下所示;

    class ShowModal2 extends Component {
      constructor(props){
        super(props);
        this.MyScrollView = React.createRef();
      }
    
      go = () => {
        this.MyScrollView.current.moveToPage(2);
      };
    
      render() {
        return (
          <Modal
            style={styles.modal}
            isVisible={true}
            onBackdropPress={this.hideModal}>
            <MyScrollView ref={this.MyScrollView}>
            ......
    

    并将相同的方法应用于其他类

    class MyScrollView extends Component {
      constructor() {
        super();
        this.state = { page: '' }
        this.scrollView = React.createRef();
      }
      moveToPage(page) {
        this.scrollView.current.scrollTo({ x: ((page - 1) * device_width), y: 0, 
        animated: true });
        alert(page);
      }
    
      render() {
        return (
          <View style={styles.container}>
            <ScrollView ref={this.scrollView} showsHorizontalScrollIndicator={false} horizontal={true} pagingEnabled={true}>
          ......
    

    请从链接中检查-> https://snack.expo.io/@sdkcy/stackoverflow-unable-to-call-method

    【讨论】:

    • 谢谢你,完美。只有一件事,目前用户可以滑动到下一个视图,有没有办法阻止这种情况,只有当按下按钮时,幻灯片才应该移动。谢谢
    • 如果在 MyScrollView 类的 ScrollView 组件中添加 scrollEnabled={false},它不会滑动。请尝试告诉我。
    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2015-08-17
    • 2020-05-27
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多