首页 > 解决方案 > 如何根据选定的选择器动态呈现视图?

问题描述

我需要解决方案和帮助,我是 reactJS 和 react-native 的新手。我想根据选定的选择器值呈现组件视图,这是我的代码示例

import { View, Text } from "react-native";
import { Picker } from "@react-native-picker/picker";
import { infoA } from "./InfoA";
import { infoB } from "./InfoB";
import { infoC } from "./InfoC";

export default class PickerSample extends Component {
  constructor(props){
    super(props);
    this.state = {
      selected: undefined
    };
  }
  onValueChange(value: string) {
    this.setState({
      selected: value
    });
  }
  render(){
    return(
      <View>
        <Picker
          selectedValue={this.state.selected}
          onValueChange={this.onValueChange.bind(this)}
        >
          <Picker.Item label="Information Item A" value=<InfoA/> />
          <Picker.Item label="Information Item B" value=<InfoB/> />
          <Picker.Item label="Information Item C" value=<InfoC/> />
        </Picker>
        {this.state.selected}
      </View>
    )
  }
}

是否可以像这样将组件呈现为选择器的值?或者我应该使用switch()函数还是.map()函数?或者也许有任何其他有效的方法来实现我想要的?

已编辑

感谢@Viet 的快速响应,如果可以像代码示例一样将组件呈现为选择器的值,我可以知道代码的哪一部分出错了吗?它返回错误

Render Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

InfoA、InfoB 和 InfoC 类组件只是一个带有单个文本组件的简单组件,这里是示例代码

import React, { Component } from "react";
import { Text } from "react-native";

export default class InfoA extends Component {
  render(){
    return(
      <Text> Information About Item A Explained Here </Text>
    )
  }
}

再次 使用带有开关功能的@Saiful Azam 的解决方案进行编辑,它仍然给我错误

Render Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

<Text>当我使用Component更改 switch 函数内的 return 语句时,它可以正常工作。这是否意味着我对 InfoA/InfoB/InfoC 组件做错了什么?这是否意味着组件未正确导出?或者还有什么问题吗?

标签: javascriptreactjsreact-native

解决方案


您可以有条件地渲染任何组件。像下面这样的东西通常用于在 2 个视图之间进行选择。您还可以使用 switch 或 if else stack 来获得多个视图。

render() {
  return (
    this.state.selected ? (<View1/>) : (<View2>);
  );
}

推荐阅读