React Native - 获取当前组件的高度,反向滚动视图

Lfa*_*Lfa 5 ios react-native

我目前正在编写一个关于 react-native version 的应用程序0.7.1。我正在尝试编写一个聊天组件。

通过聊天,您通常在底部输入文本,消息从屏幕底部推送到顶部。此外,当聊天屏幕初始化时,它会在屏幕底部初始化并允许用户向上滚动。我想在 react-native 中实现相同的行为。ScrollView 的当前行为将项目从顶部推到底部。为此,我尝试了几种不同的解决方案:

  • 第一个解决方案涉及尝试测量 ScrollView 组件。这个概念是,如果我知道视图的高度,我可以this.refs.messages.scrollTo(contentHeight)。有人提到了以下功能:this.refs.messages.measure(callbackWithTheseParams((a, b, width, height, px,py )). 但是测量函数结果是未定义的。
  • 第二种方法涉及包https://www.npmjs.com/package/react-native-invertible-scroll-view。这个包实际上也正确地对我的数据进行了排序(反向)。你可以把它想象成翻转屏幕上的像素,这样 (0,0) 是底部。这使我可以调用scrollTo(0,0). 但是,似乎此功能仅在 0.8.0-rc 中可用。我不确定它是否稳定(或者更稳定)。

编辑 - 添加示例

我的构造函数:

componentDidMount() {
    this.measureComponent()
}

// measureComponent
measureComponent() {
    console.log('this gets called');
    this.refs.messages.measure((ox, oy, width, height) => {
        console.log(height); // does not get called.  
    });
}
Run Code Online (Sandbox Code Playgroud)

我的渲染功能是:

return (
  <ScrollView 
    scrollEventThrottle={200}
    ref="messages" 
    style={styles.container}>
    <View style={styles.messages}>
      {messages.map(this.renderMessage)}
    </View>
    <TextInput
      style={styles.newMessage}
      value={this.state.message}
      onSubmitEditing={this.sendMessage}
      onChangeText={(text) => this.setState({message: text})} />
  </ScrollView>
);
Run Code Online (Sandbox Code Playgroud)

Mr *_*ker 0

我不确定是否有更简单的方法来获取 ScrollView 的高度,但我确实在 ListView 的 React Native 源代码中注意到了这一点/Libraries/CustomComponents/ListView/ListView.js

_measureAndUpdateScrollProps: function() {
  var scrollComponent = this.getScrollResponder();
  ...
  RCTUIManager.measureLayout(
    scrollComponent.getInnerViewNode(),
    React.findNodeHandle(scrollComponent),
    logError,
    this._setScrollContentLength
  );
  ...
},
_setScrollContentLength: function(left, top, width, height) {
  this.scrollProperties.contentLength = !this.props.horizontal ?
    height : width;
},
Run Code Online (Sandbox Code Playgroud)

根据horizontal属性是否设置,它获取高度或宽度。RCTUIManager是本机模块 module ( require('NativeModules').UIManager) 的一部分。