0

我无法访问 FlatList 中的组件 ref child。在 componentDidMount 方法上,我只有一个 FlatList 的参考。

如果您想重现它,这是我的代码:

import React, { Component } from "react";
import {
  AppRegistry,
  FlatList,
  StyleSheet,
  Text,
  View
} from "react-native";

export default class touchable extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref="REF-FLATLIST"
          data={[{ key: "a" }, { key: "b" }]}
          renderItem={({ item }) =>
            <Text ref={`REF-FLATLIST${item.key}`}>
              {item.key}
            </Text>}
        />
      </View>
    );
  }
  componentDidMount() {
    console.log(this.refs);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});

AppRegistry.registerComponent("touchable", () => touchable);

我正在使用 React Native v0.45.1。

4

1 回答 1

7

您可以通过以下方式使用 ref 回调将其设置为 ref:

import React, { Component } from "react";
import {
  AppRegistry,
  FlatList,
  StyleSheet,
  Text,
  View
} from "react-native";

export default class touchable extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref="REF-FLATLIST"
          data={[{ key: "a" }, { key: "b" }]}
          renderItem={({ item }) =>
              <Text ref={(ref) => this.textRef = {...this.textRef, [`REF-FLATLIST${item.key}`]: ref}}>
                {item.key}
              </Text>}
            />
          </View>
    );
  }
  componentDidMount() {
    console.log(this.refs, this.textRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});

于 2017-06-29T05:47:30.867 回答