【问题标题】:How to import React object: elements via module.exports and render inside component?如何通过 module.exports 导入 React 对象:元素并在组件内渲染?
【发布时间】:2017-11-12 05:57:33
【问题描述】:

我正在尝试从外部文件导入和呈现 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>;

【问题讨论】:

    标签: reactjs react-css-modules


    【解决方案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

    【讨论】:

    • 嗨 Krasimir.. 哎呀.. 是的,解决了它!谢谢。
    猜你喜欢
    • 2023-01-11
    • 2017-08-18
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2018-11-29
    相关资源
    最近更新 更多