首页 > 解决方案 > 如何在本机反应中制作动态标签视图屏幕

问题描述

我正在尝试在我的反应本机应用程序中添加选项卡。在选项卡上,我想显示来自 api 的所有数据。这给出了一个数组string。当用户单击任何选项卡时,它应该显示相应的数据。这是一个示例图像。

在标题下方,我想显示来自 ap 的字符串数组。在搜索字段下方,我想显示来自不同 api 的数据。

我正在使用一个包https://www.npmjs.com/package/react-native-tab-view 。我不知道如何用这个来实现这一点。

状态图像

这是我的代码

import { TabView, SceneMap } from "react-native-tab-view";
import { connect } from "react-redux";
import { getAllState } from "../../actions/hubActions";

interface CommunityMemberProps {
  getStates: () => void;
  allStates: [];
}
const styles = StyleSheet.create({
  scene: {
    flex: 1,
  },
});

const FirstRoute = () => (
  <View style={[styles.scene, { backgroundColor: "#ff4081" }]} />
);

const SecondRoute = () => (
  <View style={[styles.scene, { backgroundColor: "#673ab7" }]} />
);

const initialLayout = { width: Dimensions.get("window").width };

const CommunityMember = ({ getStates, allStates }: CommunityMemberProps) => {
  useEffect(() => {
    getStates();   
  }, []);
  const [searchText, setSearchText] = useState<string>("");
  const handleChangeText = (text: string) => {
    setSearchText(text);
  };
  console.log("allStates", allStates);  <-- this gives data ["India", "newDelhi"]

  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: "First", title: "First" },
    { key: "Second", title: "Second" },
  ]);


  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });
  return (
    <TabView
      navigationState={{ index, routes }}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
    />
  );
};

function mapStateToProps(state: any) {
  return {
    allStates: state.hub.allStates,
  };
}
const mapDispatchToProps = (dispatch: any) => ({
  getStates: () => dispatch(getAllState()),
});

export default connect(mapStateToProps, mapDispatchToProps)(CommunityMember);

标签: reactjsreact-native

解决方案


由于您使用的是 redux,因此可以轻松完成。每当您选择一个选项卡时,都会使用选定的选项卡更新 redux 状态。保持所有选项卡的组件相同,并使用 mapStateToProps 从 redux 状态检索选项卡,并动态获取数据并使用 useEffect 或 componentDidMount() 挂钩。


推荐阅读