React Native:访问FlatList中的组件引用子项

时间:2017-06-28 21:54:51

标签: react-native react-native-flatlist

我无法访问FlatList中的组件引用子项。在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。

1 个答案:

答案 0 :(得分:4)

你可以用这种方式使用ref回调设置ref:

&#13;
&#13;
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"
  }
});
&#13;
&#13;
&#13;