如何在React Native中添加多个组件?

时间:2017-07-17 09:21:42

标签: javascript ios reactjs react-native expo

注意:我是React Native的新用户并且已经搜索了如何执行此操作但没有找到有用的结果我正在使用React Native创建应用并希望添加多个组件,例如文本,按钮和文本输入空间,但在没有收到错误的情况下这样做很麻烦。有没有办法使用React Native?将多个组件包含到一个javascript文档中?

我目前的代码:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Text style={styles.bigblack}>Sample Bold Text Here</Text>
        <Text>Sample Text Here:</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bigblack: {
    color: 'black',
    fontWeight: 'bold',
    fontSize: 28,
  },
  red: {
    color: 'red',
  },
  container: {
    flex: 1,
    backgroundColor: '#fdf5e6',
    alignItems: 'center',
    justifyContent: 'center',
  },

});

代码我想为文字输入添加:

class UselessTextInput extends Component {
  render() {
    return (
      <TextInput
        {...this.props} 
        editable = {true}
        maxLength = {40}
      />
    );
  }
}

export default class UselessTextInputMultiline extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 'Useless Multiline Placeholder',
    };
  }

  render() {
    return (
     <View style={{
       backgroundColor: this.state.text,
       borderBottomColor: '#000000',
       borderBottomWidth: 1 }}
     >
       <UselessTextInput
         multiline = {true}
         numberOfLines = {4}
         onChangeText={(text) => this.setState({text})}
         value={this.state.text}
       />
     </View>
    );
  }
}

代码我想为Button添加:

<Button
  onPress={onPressLearnMore}
  title="Learn More"
  color="#841584"
  accessibilityLabel="Learn more about this button"
/>

1 个答案:

答案 0 :(得分:2)

您可以在同一文档中创建多个组件,但export default只能创建一个。

所以你可以创建如下的多个组件:

export class UselessTextInput {}

export class UselessTextInputMultiline {}

export class Button {}
访问时

import {UselessTextInput, UselessTextInputMultiline, Button} from './components/customInput' // change with your respective path

如果您仍想要单export default,那么:

export default class UselessTextInputMultiline {}

并在导入时

import Template,{Button} from './components/customInput'

对于,导出多个组件:

module.exports = {
    text: UselessTextInput,
    btn: Button
}

导入将如下:

let txtInput= require('./components/customInput').text;
let btnInput = require('./components/customInput').btn;