1

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

这在导入“文本”时有效,但是我无法让它在导入 React“元素”时工作。

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

(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>;
4

1 回答 1

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变量未提升,因此您导出undefinedfirstColumn.

于 2017-06-10T08:06:13.703 回答