包括来自App.js中另一个文件的自定义渲染代码

时间:2018-03-14 07:00:47

标签: javascript reactjs react-native

如何使部分代码不对另一个文件中的组件做出反应?

由于

{this.state.test &&
<View>......</View> // i want to bring this code from another file here  with a shortcut import etc
}

2 个答案:

答案 0 :(得分:0)

您可以从其他文件导入组件。

1-)创建包含视图代码和索引文件的组件文件夹,如;

-components
--MyView.js
--index.js

-App.js

2-)在你的App.js中填写想要看到的内容的MyView课程

<强> MyView.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class MyView extends Component {
   constructor(props) {
      super(props);
   }

   render() {
      <View>...<View>
   }
}

MyView.propTypes = {
  props you want to use it...
};

module.exports = MyView;

<强> index.js

import MyView from './components';

module.exports = {
  MyView,
};

3-)将MyView类导入App.js并使用它;

<强> App.js

import { MyView } from './components';

{this.state.test &&
<MyView>...give some props that you want to see here...</MyView>
}

当您想要在许多页面中使用它们时,从外部导入视图或组件非常有用,您应该提供特定的道具,如样式值或某些数据。否则,如果您只使用一次,则根本没有必要。

答案 1 :(得分:0)

您可以将这些类型的代码组织到辅助函数中,例如UIHelper.js:

function renderImageIcon(iconName, width = 32, height = 32, tintColor) {
    return (<Image
                source={localImageUrl[iconName]}
                style={[{
                    width: width,
                    height: height,
                    tintColor: tintColor
                }]}
            />)        
}

const UIHelper = {
    renderLabel: renderLabel,           //Other helper functions
    renderImageIcon: renderImageIcon,   //Expoert this
    renderDateTime: renderDateTime,     //Other helper functions
    ...
}
export default UIHelper;

用法:

import UIHelper from '../what/ever/path/UIHelper'

render (){
...
   {UIHelper.renderImageIcon("search", 40, 40)}
...
}