如何通过module.exports导入React对象:元素并在组件内部渲染?

时间:2017-06-10 07:54:06

标签: reactjs react-css-modules

我正在尝试导入和渲染一个对象:React' element'从外部文件导入并使用module.exports将其导入包含Component的另一个文件并在Component中呈现它。该组件之前已被调用3次,以创建3列并用文本填充它们。

导入' text'但是,我无法将其用于导入React'元素'。

我需要做些什么来渲染导入的React'元素'?我也在使用css-modules。下面是代码。感谢: -

(File: column.css)
.default {
  box-sizing: border-box;
  border: 1px solid black;
  font-size: 20px;
  width: 32%;
  height: auto;
}

.red  {
  composes: default;
  float: left;
  margin-right: 2%;
  background-color: red;
}

.green  {
  composes: default;
  float: left;
  background-color: green;
}

.blue {
  composes: default;
  float: right;
  margin-left: 2%;
  background-color: white;
}


(File: Home.js)
import React from 'react'
import Column from '../components/Column'
import styles from './home.css'

export default class Home extends React.Component {
  render() {
    return (
      <div className={styles.container}>
        <h1>Home</h1>
        <Column style = {'red'} content={'firstColumn'}/>
        <Column style = {'green'} content={'secondColumn'}/>
        <Column style = {'blue'} content={'thirdColumn'}/>
      </div>
    )
  }
}


(File: Column.js)
import React from 'react'
import style from './column.css'
const contents = require( '../components/content')

export default class Column extends React.Component {
  render() {
    return (
        <div className={style[this.props.style]}>
          {contents[this.props.content]}
        </div>
    )
  }
}


(File: content.js)
import React from "react"

module.exports = {
  firstColumn: text,
  secondColumn: "This text is rendered",
  thirdColumn: "This text is rendered",
}

const text = <p>This element text is NOT rendered</p>;

1 个答案:

答案 0 :(得分:1)

嗯...不应该是content.js的样子:

const text = <p>This element text is NOT rendered</p>;

module.exports = {
  firstColumn: text,
  secondColumn: "This text is rendered",
  thirdColumn: "This text is rendered",
}

text变量未被提升,因此您将undefined导出为firstColumn