从字符串数组中渲染反应组件的动态列表

时间:2017-05-04 11:32:46

标签: reactjs react-jsx

我的组件是一个过滤器,它接收一些应该呈现的过滤器。但是不呈现道具:

<Filter key={i}/>

代码在这里:https://www.webpackbin.com/bins/-KjI4MiSjlV69O_zaOCD

过滤器组件:

import React, { PropTypes } from 'react'
import Filter1 from './Filter1'
import Filter2 from './Filter2'


const Filters = ({ filters }) => (
  <div>
    { filters.reverse().map((Filter, i) =>
       // React.createElement(Filter, { key: i}) does not work
       // <p>{Filter}</p> // h
       <Filter key={i}/>

    )}
    <p> This should be seen twice!</p>
    <Filter1/>
    <Filter2/>
  </div>
)
Filters.propTypes = {
  filters: PropTypes.arrayOf(PropTypes.string).isRequired
}

export default Filters

其中一个过滤器:

import React from 'react'

function Filter1 () {
  return (
    <h1>This is filter1</h1> 
  )
}

export default Filter1

1 个答案:

答案 0 :(得分:1)

像这样更改Filters.js

import React, { PropTypes } from 'react'
import Filter1 from './Filter1'
import Filter2 from './Filter2'

const filters = {
  Filter1: Filter1,
  Filter2: Filter2
}
const Filters = (props) => (
  <div>
    { props.filters.reverse().map((filter, i) => {
        const Filter = filters[filter];
        return <Filter key={i}/>
      })
    }
    <p> This should be seen twice!</p>
    <Filter1/>
    <Filter2/>
  </div>
)
Filters.propTypes = {
  filters: PropTypes.arrayOf(PropTypes.string).isRequired
}

export default Filters

关键更改是使用一个对象filters,该对象包含与您传入的字符串匹配的键。值是您要呈现的组件。

Here是已编辑的webpackbin