如何从导入的组件调用和使用类

时间:2020-05-12 07:18:22

标签: react-native

我试图在我的模式中添加一个存根朋友选择器,但是我不知道如何使用导入的类。这是我导入friendSelector的页面:

/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { Text, TextInput, View, StyleSheet, Button, Modal, TouchableOpacity, Image } from 'react-native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Scan from './Scan';
import Kowops from './Kowops';
import Wallet from './Wallet';
import friendSelector from './forms/friendSelector';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';
import ImagePicker from 'react-native-image-picker';

export class Main extends Component {
  constructor(props) {
    super(props);
    this.state = { name: '' };
    this.state = { description: '' };
    this.state = { who: '' };
    this.state = { resourcePath: {}, };
  }
  static navigationOptions = {
    headerRight: (
      <Button
        onPress={() => alert('This is a button!')}
        title="Info"
        color="#fff"
      />
    ),
  };
  state = {
    isVisible: false
  };

  // hide show modal
  displayModal(show) {
    this.setState({ isVisible: show })
  }


  selectFile = () => {
    var options = {
      title: 'Select Image',
      customButtons: [
        {
          name: 'customOptionKey',
          title: 'Choose file from Custom Option'
        },
      ],
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };

    ImagePicker.showImagePicker(options, res => {
      console.log('Response = ', res);

      if (res.didCancel) {
        console.log('User cancelled image picker');
      } else if (res.error) {
        console.log('ImagePicker Error: ', res.error);
      } else if (res.customButton) {
        console.log('User tapped custom button: ', res.customButton);
        alert(res.customButton);
      } else {
        let source = res;
        this.setState({
          resourcePath: source,
        });
      }
    });
  };



  render() {
    return (
      <View style={styles.container}>
        <View style={styles.bodyContainer}>
          <Text style={styles.plainText} onPress={() => this.props.navigation.navigate('Register')}>
            This is the main page, return to registration
             </Text>
          <View style={{ height: 5 }}></View>
        </View>
        <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.state.isVisible}
        >
          <View style={styles.modalContainer}>
            <View style={styles.modalTopRow}>
              <View style={styles.modalTopRowContainer}>
                <View style={styles.modalTopRowContainerCell}>

                </View>
                <View style={styles.modalTopRowContainerCell}>
                  <Text style={styles.titleText}>Add!</Text>
                </View>
                <View style={styles.modalTopRowContainerCellRight}>
                  <Icon name="ios-close" style={{ fontSize: 40 }} onPress={() => this.displayModal(false)} />
                </View>
              </View>
            </View>
            <View style={styles.modalBody}>
              <View style={{ height: 100 }}></View>
              <TextInput
                style={styles.inputTextField}
                placeholder="Name"
                value={this.state.text}
                backgroundColor="white"
                onChangeText={name => this.setState({ name })}
              />
              <View style={{ height: 20 }}></View>
              <TextInput
                style={styles.multilineInputTextField}
                placeholder="description"
                value={this.state.text}
                multiline={true}
                backgroundColor="white"
                onChangeText={description => this.setState({ description })}
              />
              <View style={{ height: 20 }}></View>
              <Image
                source={{ uri: this.state.resourcePath.uri }}
                style={{ width: 200, height: 200 }}
              />
              <View style={{ height: 20 }}></View>
              <TouchableOpacity onPress={this.selectFile} style={styles.buttonContainer}  >
                <Text style={styles.buttonText}>add an image</Text>
              </TouchableOpacity>
            </View>
            <View style={{ height: 20 }}></View>
            <View>
              <friendSelector> </friendSelector>
            </View>
          </View>
        </Modal>


        <ActionButton buttonColor="#c5e1a5">
          <ActionButton.Item
            style={styles.actionButtonItem}
            buttonColor='#c5e1a5'
            title="Add a thing"
            onPress={() => this.displayModal(true)}
          >
            <Icon name="ios-add-circle" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item
            style={styles.actionButtonItem}
            buttonColor='#c5e1a5'
            title="check-in"
            onPress={() => console.log('notes tapped!')}
          >
            <Icon name="ios-qr-scanner" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item
            style={styles.actionButtonItem}
            buttonColor='#c5e1a5'
            title="check-out"
            onPress={() => console.log('notes tapped!')}
          >
            <Icon name="ios-barcode" style={styles.actionButtonIcon} />
          </ActionButton.Item>
        </ActionButton>

      </View>
    )
  }
}

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator
      tabBarOptions={{
        activeTintColor: 'black',
        inactiveBackgroundColor: '#c5e1a5',
        inactiveTintColor: 'gray',
        labelStyle: { fontSize: 16 },
        style:
        {
          backgroundColor: '#c5e1a5',
          borderTopColor: 'transparent',
          padding: 0,
          activeTabStyle: {
            fontWeight: 'bold',
          }
        },
        tabStyle: {
          borderRightColor: 'white',
          borderRightWidth: 1,
        }
      }}>


      <Tab.Screen name="Main" component={Main} />
      <Tab.Screen name="Scan" component={Scan} />
      <Tab.Screen name="Wallet" component={Wallet} />
      <Tab.Screen name="Kowops" component={Kowops} />
    </Tab.Navigator>
  );
}

export default function BottomNav() {
  return (

    <MyTabs />

  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    padding: 10,
    alignItems: 'stretch',
    justifyContent: 'space-around',
  },
  headerContainer: {
    height: 60,
    width: 420,
    padding: 0,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#c5e1a5',
  },
  bodyContainer: {
    height: 250,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  logo: {
    height: 50,
    width: 165
  },
  formContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'

  },
  buttonContainer: {
    padding: 10,
    marginBottom: 20,
    width: 250,
    alignItems: 'center',
    backgroundColor: '#c5e1a5',
  },
  inputTextField: {
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 10,
    height: 40,
    width: 250,
    marginBottom: 10,
    fontSize: 16,
    borderBottomWidth: 1.0,
  },
  multilineInputTextField: {
    alignItems: 'center',
    padding: 10,
    justifyContent: 'space-between',
    height: 100,
    width: 250,
    marginBottom: 10,
    fontSize: 16,
    borderWidth: 1.0,
  },


  plainText: {
    fontSize: 16,
    marginBottom: 5,
    color: '#59616e',
    textDecorationLine: 'underline',
  },
  titleText: {
    fontSize: 24,
    marginBottom: 5,
    color: '#59616e',
  },
  actionButtonIcon: {
    fontSize: 20,
    height: 22,
    color: 'white',
  },
  modalContainer: {
    //flexDirection: 'column',
    padding: 10,
    flex: 8,
    alignItems: 'stretch',
    justifyContent: 'space-around',
    alignContent: 'stretch',
    flexWrap: 'nowrap',
    // height: 800,
    // width: 400,
  },
  modalTopRow: {
    alignContent: 'stretch',
    flex: 1,


  },
  modalTopRowContainer: {
    flex: 3,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  modalTopRowContainerCell: {
    flex: 1,
    alignContent: 'center',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  modalTopRowContainerCellRight: {
    flex: 1,
    padding: 10,
    alignContent: 'flex-start',
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
  },
  modalBody: {
    flexDirection: 'column',
    flex: 7,
    alignContent: 'center',
    justifyContent: 'flex-start',
    alignItems: 'center',

  },
  modalBodyContainer: {
  },

});

并且我确定friendSelector类已导入。这是form / friendSelector.js文件的文件:

import React, { Component } from 'react';
import { View } from 'react-native';
import MultiSelect from 'react-native-multiple-select';

export default class friendSelector extends Component {

  state = { selectedItems: [] };

  items = [{
    id: '92iijs7yta',
    name: 'Kenneth',
  }, {
    id: 'a0s0a8ssbsd',
    name: 'Ann',
  }, {
    id: '16hbajsabsd',
    name: 'Leen',
  }, {
    id: 'nahs75a5sg',
    name: 'Kris',
  }, {
    id: '667atsas',
    name: 'Steve',
  }, {
    id: 'suudydjsjd',
    name: 'Sarah',
  }];

  onSelectedItemsChange = selectedItems => {
    this.setState({ selectedItems });
  };

  render() {
    const { selectedItems } = this.state;
    return (
      <View style={{ flex: 1 }}>
        <MultiSelect
          hideTags
          items={items}
          uniqueKey="id"
          ref={(component) => { this.multiSelect = component }}
          onSelectedItemsChange={this.onSelectedItemsChange}
          selectedItems={selectedItems}
          selectText="Pick friend(s)"
          searchInputPlaceholderText="Search..."
          onChangeInput={(text) => console.log(text)}
          tagRemoveIconColor="#CCC"
          tagBorderColor="#CCC"
          tagTextColor="#CCC"
          selectedItemTextColor="#CCC"
          selectedItemIconColor="#CCC"
          itemTextColor="#000"
          displayKey="name"
          searchInputStyle={{ color: '#CCC' }}
          submitButtonColor="#CCC"
          submitButtonText="Submit"
        />
        <View>
          {this.multiSelect.getSelectedItemsExt(selectedItems)}
        </View>
      </View>
    );
  }
}

现在,我正在尝试像这样调用friendselector:

<friendSelector> </friendSelector>

JSX元素,但我想这种方式是不可能的。谁能指出我正确的方向?我一直在寻找教程,但似乎找不到很好的解释方法。

这是我收到的错误消息:

    Error: Text strings must be rendered within a <Text> component.

    This error is located at:
        in friendSelector (at main.js:134)
        in RCTView (at main.js:133)
        in RCTView (at main.js:90)
        in RCTView (at AppContainer.js:109)
        in RCTView (at AppContainer.js:135)
        in AppContainer (at Modal.js:254)
        in RCTView (at Modal.js:276)
        in RCTModalHostView (at Modal.js:262)
        in Modal (at main.js:85)
        in RCTView (at main.js:78)
        in Main (at SceneView.tsx:98)
        in StaticContainer
        in StaticContainer (at SceneView.tsx:89)
        in EnsureSingleNavigator (at SceneView.tsx:88)
        in SceneView (at useDescriptors.tsx:125)
        in RCTView (at BottomTabView.tsx:42)
        in SceneContent (at BottomTabView.tsx:127)
        in RCTView (at ResourceSavingScene.tsx:44)
        in RCTView (at ResourceSavingScene.tsx:27)
        in ResourceSavingScene (at BottomTabView.tsx:122)
        in RCTView (at screens.native.js:132)
        in ScreenContainer (at BottomTabView.tsx:106)
        in RCTView (at BottomTabView.tsx:105)
        in SafeAreaProviderCompat (at BottomTabView.tsx:104)
        in BottomTabView (at createBottomTabNavigator.tsx:41)
        in BottomTabNavigator (at main.js:176)
        in MyTabs (at main.js:209)
        in BottomNav (at SceneView.tsx:98)
        in StaticContainer
        in StaticContainer (at SceneView.tsx:89)
        in EnsureSingleNavigator (at SceneView.tsx:88)
        in SceneView (at useDescriptors.tsx:125)
        in RCTView (at CardContainer.tsx:199)
        in RCTView (at CardContainer.tsx:198)
        in RCTView (at CardSheet.tsx:33)
        in ForwardRef(CardSheet) (at Card.tsx:526)
        in RCTView (at createAnimatedComponent.js:144)
        in AnimatedComponent (at createAnimatedComponent.js:194)
        in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:508)
        in PanGestureHandler (at GestureHandler.native.tsx:13)
        in PanGestureHandler (at Card.tsx:502)
        in RCTView (at createAnimatedComponent.js:144)
        in AnimatedComponent (at createAnimatedComponent.js:194)
        in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:498)
        in RCTView (at Card.tsx:492)
        in Card (at CardContainer.tsx:164)
        in CardContainer (at CardStack.tsx:497)
        in RCTView (at Screens.tsx:70)
        in MaybeScreen (at CardStack.tsx:490)
        in RCTView (at Screens.tsx:48)
        in MaybeScreenContainer (at CardStack.tsx:388)
        in CardStack (at StackView.tsx:433)
        in KeyboardManager (at StackView.tsx:431)
        in RNCSafeAreaView (at src/index.tsx:28)
        in SafeAreaProvider (at SafeAreaProviderCompat.tsx:42)
        in SafeAreaProviderCompat (at StackView.tsx:428)
        in RCTView (at StackView.tsx:427)
        in StackView (at createStackNavigator.tsx:82)
        in StackNavigator (at App.js:22)
        in EnsureSingleNavigator (at BaseNavigationContainer.tsx:288)
        in ForwardRef(BaseNavigationContainer) (at NavigationContainer.tsx:66)
        in ThemeProvider (at NavigationContainer.tsx:65)
        in ForwardRef(NavigationContainer) (at App.js:21)
        in App (at renderApplication.js:45)
        in RCTView (at AppContainer.js:109)
        in RCTView (at AppContainer.js:135)
        in AppContainer (at renderApplication.js:39)

    createTextInstance
        ReactNativeRenderer-dev.js:4289:15
    completeWork
        ReactNativeRenderer-dev.js:17024:55
    completeUnitOfWork
        ReactNativeRenderer-dev.js:20912:27
    performUnitOfWork
        ReactNativeRenderer-dev.js:20882:29
    workLoopSync
        ReactNativeRenderer-dev.js:20848:38
    performSyncWorkOnRoot
        ReactNativeRenderer-dev.js:20456:22
    performSyncWorkOnRoot
        [native code]:0
    runWithPriority$argument_1
        ReactNativeRenderer-dev.js:5703:31
    unstable_runWithPriority
        scheduler.development.js:818:23
    flushSyncCallbackQueueImpl
        ReactNativeRenderer-dev.js:5698:21
    flushSyncCallbackQueue
        ReactNativeRenderer-dev.js:5686:28
    batchedUpdates$1
        ReactNativeRenderer-dev.js:20575:28
    batchedUpdates
        ReactNativeRenderer-dev.js:2731:29
    _receiveRootNodeIDEvent
        ReactNativeRenderer-dev.js:2834:16
    receiveTouches
        ReactNativeRenderer-dev.js:2911:27
    __callFunction
        MessageQueue.js:425:19
    __guard$argument_0
        MessageQueue.js:112:6
    __guard
        MessageQueue.js:373:10
    callFunctionReturnFlushedQueue
        MessageQueue.js:111:4
    callFunctionReturnFlushedQueue
        [native code]:0

非常感谢您的帮助!

蒂姆

1 个答案:

答案 0 :(得分:0)

我通过更改解决了这个问题

从“ ./forms/friendSelector”导入friendSelector; 至 从'./forms/friendSelector'导入 F riendSelector;

还要重命名该类,使其以大写字母F开头

导出默认类 F riendSelector扩展了组件{

我收到另一个错误,所以我想我已经解决了这个问题。