注意:我是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"
/>

最佳答案

您可以在同一文档中创建多个组件,但只能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;

关于javascript - 如何在React Native中添加多个组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45140368/

10-09 04:05