【问题标题】:TypeError: Cannot read property 'measure' of undefinedTypeError:无法读取未定义的属性“度量”
【发布时间】:2017-10-16 15:37:20
【问题描述】:

我对 react native 的度量有疑问:

checkPositionComponant = (id) => {
    this.refs.component.measure((a, b, width, height, pageX, pageY) => {
      tabTag[id].positionY = pageY;
     });
  }

  componentTag() {
   return tabTag.map((item, id) => {
      return(
        <View key={id} style={styles.componentView} ref="component">
          { this.checkPositionComponant(id) }
        </View>
      );
    });
  }

我的错误是:TypeError: Cannot read property 'measure' of undefined

【问题讨论】:

  • 这意味着this.refs.component是未定义的
  • 是否正在渲染?
  • 正在渲染是什么意思? componentTag 在我的渲染方法中被调用,就像 { this.componentTag() }

标签: javascript reactjs react-native native


【解决方案1】:
  1. 您在多个组件上使用相同的 ref

  2. 来自react docs

永远不要在任何组件的 render 方法中访问 refs——或者当任何组件的 render 方法甚至在调用堆栈中的任何位置运行时。

您可能希望将代码与 react 的生命周期对齐并使用

componentDidMount() {
    this.checkPositionComponant(id);
}

checkPositionComponant 应更改状态(setState / dispatch)以使组件重新渲染。

看看this example

【讨论】:

    【解决方案2】:

    我遇到了同样的错误。 这在 ios 中工作正常,但对于 android,它返回 undefined 除非 您在 onLayout 属性上放置了空回调。 您可以在视图组件中执行此操作:-

    <View key={id} style={styles.componentView} ref="component" onLayout={() => {}}>
         { this.checkPositionComponant(id) }
    </View>
    

    如果你想了解更多,you can read this issue on github

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2015-02-18
      • 2016-09-05
      • 2021-12-05
      • 2020-07-20
      相关资源
      最近更新 更多