react-native - 如何通过ref访问react-native listview子组件?

标签 react-native react-native-listview

如何访问 react-native listview通过 ref 的子组件?

class MyComponent extends Component {
  constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6']),
    };
  }

  onTap() {
    console.log(this.refs)
    /* After getting touchComponent refs below block of code has to be executed.
    that.refs.touchComponent.measure((ox, oy, width, height, px, py) => {
    this.setState({
       isVisible: true,
       buttonRect: {x: px, y: py, width: width, height: height}
    });
  });
  */
 }

  render() {
    return (
      <ListView ref="listView"
        dataSource={this.state.dataSource}
        renderRow={(rowData) => <TouchableHighlight ref="touchComponent" onPress={this.onTap.bind(this)}><Text>{rowData}</Text></TouchableHighlight>}
      />
    );
  }
}
console.log(this.refs) 版画 Object {listView: Object}
我如何访问 TouchableHighlight组件引用?

我经历了React Native: Refs in ListViewReact Native - get refs of custom components in listview from renderRow但我不明白他们是怎么做的。

最佳答案

您无法通过在 ListView 中添加 refs 的字符串方式访问 refs,您必须使用回调技术来应用 refs

 <ListView ref="listView"
        dataSource={this.state.dataSource}
        renderRow={(rowData) => <TouchableHighlight ref={(TouchableHighLight) => { this.button = TouchableHighLight; }} onPress={this.onTap.bind(this)}><Text>{rowData}</Text></TouchableHighlight>}
      />

但很可能即使在获得 ref 之后,您也无法访问测量方法。要获取 pageX 和 pageY,您可以通过 onPress 传递触摸事件并使用 nativeEvent 像这样获取 pageX 和 pageY,您可以使用 measureInWindow 方法获取宽度和高度:-
onPress={(event) => this.onTap(event)}

方法定义可能是这样的:-
onTap(evnt) {
  var py=evnt.nativeEvent.pageY
  var px=evnt.nativeEvent.pageX
  console.log(this.refs)
this.button.measureInWindow(x,y,width,height)
  this.setState({
       isVisible: true,
       buttonRect: {x: x, y: y, width: width, height: height}
  });
});
}

关于react-native - 如何通过ref访问react-native listview子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719551/

相关文章:

listview - react native ListView 某些行不显示

react-native - 如何创建图像文件和 'Save to Camera Roll'

android - React Native无法确定任务 ':app:compileDebugJavaWithJavac'的依赖关系

javascript - React Native,状态项的值设置不正确

javascript - 如何根据纬度和经度获取两个位置之间的距离?

javascript - Concat 实际上是连接而不是添加到数组。 react native JavaScript

react-native - React Native ListView Insets

react-native - 如何处理 ListView 排序性能?

javascript - 调用具有单个 Promise 参数的 native 模块的 JS 语法是什么?

reactjs - 在 React 函数式组件中每 X 秒调用一次 API