【问题标题】:React Native : Access to component ref child in FlatListReact Native:访问 FlatList 中的组件引用子项
【发布时间】:2017-06-28 21:54:51
【问题描述】:

我无法访问 FlatList 中的组件 ref child。在 componentDidMount 方法中,我只有一个 FlatList 的 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-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。

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

    您可以通过这种方式使用 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"
      }
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2020-05-24
      相关资源
      最近更新 更多