1

我想知道如何在 FlatList 属性上使用 React Navigation,其中Stack.Screen的名称来自.json文件。

这样,当用户单击该项目时,他们会转到应用程序的另一个页面。

数据

{
  Data: [
    {
      "key": "0",
      "label": "Test",
      "goTo": "Test", <--- Here goes the name of Stack.Screen from routes.js
    }
  ]
}

平面列表结构

function Item({ label, goTo }) {
  return (
    <Ripple rippleCentered onPressIn={goTo}> // (react-native-material-ripple)
      <Option>
        <Icon name={onIcon} size={28} color={onColor} /> // (react-native-vector-icons)
        <OptionLabel color={onColor}>{label}</OptionLabel>
      </Option>
    </Ripple>
  );
}

我已经尝试使用Ripplenavigation.navigate({goTo})onPressIn属性,但出现 ReferenceError:找不到变量:导航

最终导出的组件

export default class Menu extends Component {
  render() {
    return (
      <Container color={this.props.color}>
        <FlatList
          data={Data}
          showsVerticalScrollIndicator={false}
          keyExtractor={item => item.key}
          numColumns={5}
          columnWrapperStyle={Styles.Row}
          renderItem={({ item }) =>
            <Item
              goTo={item.goTo}
              label={item.label}
            />
          }
        />
      </Container>
    );
  }
}
4

1 回答 1

1

从 json 文件中读取

import json from './myfile.json'; // reading from json file

export default class Menu extends Component {
  render() {
    return (
      <Container color={this.props.color}>
        <FlatList
          data={json.Data} // accessing Data from json
          showsVerticalScrollIndicator={false}
          keyExtractor={item => item.key}
          numColumns={5}
          columnWrapperStyle={Styles.Row}
          renderItem={({ item }) =>
            <Item
              goTo={item.goTo}
              label={item.label}
            />
          }
        />
      </Container>
    );
  }
}

导航

你可以使用useNavigation钩子来调用navigation.navigate(goTo)

例如

import { useNavigation } from '@react-navigation/native';

function Item({ label, goTo }) {
  const navigation = useNavigation(); // navigation hook

  return (
    <Ripple rippleCentered onPressIn={() => navigation.navigate(goTo)}> // navigate to goTo screen
      <Option>
        <Icon name={onIcon} size={28} color={onColor} />
        <OptionLabel color={onColor}>{label}</OptionLabel>
      </Option>
    </Ripple>
  );
}

请注意,Menu需要下NavigationContainer才能useNavigation工作。

于 2020-02-27T16:22:57.027 回答