React Native - 如何将jsx和样式移动到单独的文件中

时间:2018-01-28 12:12:38

标签: reactjs react-native

我有一个物品模块。我想分离处理jsx和样式的代码,以便它们不是全部在一个文件中。

items.screen.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native';
import s from './items.style'
import template from './items.template';

export default class ItemsScreen extends Component {

    static navigationOptions = {
        title: "Items"
    }

    constructor(props) {
        super(props);
        this.state = { text: 'Useless Placeholder' };
    }

    render() {

    }

}

items.template.js

return (
    <View style={s.container}>
        <TextInput
            style={{ width: 300 }}
            value={this.state.text}
            onChangeText={(text) => this.setState({ text })}
        />
    </View>
);

items.style.js

import {StyleSheet} from 'react-native'

const ItemsStyle = StyleSheet.create({
    container: {
        flex: 1,
        padding: 20,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
});

export default ItemsStyle;

我现在如何渲染现在位于.template文件中的jsx代码,请记住我需要确保我可以访问&#34;这个&#34;变量和样式表变量。

1 个答案:

答案 0 :(得分:0)

在模板文件中,为什么不将其创建为组件,然后在屏幕文件中呈现组件?

<强> items.screen.js

import React, { Component } from 'react';
import Template from './items.template';

export default class ItemsScreen extends Component {

  static navigationOptions = {
      title: "Items"
  }

  constructor(props) {
      super(props);
      this.state = { text: 'Useless Placeholder' };
  }

  render() {
     return <Template />
  }

}

<强> items.template.js

import { View, TextInput } from 'react-native';
import { styles } from './items.styles'

const Template = () => (
   <View style={styles.container}>
      <TextInput
        style={{ width: 300 }}
        value={this.state.text}
        onChangeText={(text) => this.setState({ text })}
      />
   </View>
);

export default Template;

<强> items.styles.js

import { StyleSheet } from 'react-native'

export const styles= StyleSheet.create({
    container: {
        flex: 1,
        padding: 20,
        backgroundColor: '#fff',
        alignItems: 'center',
       justifyContent: 'flex-start',
    },
});

那样的东西?