用字符串 Reactjs 替换 Class 名称

Replacing Class Names by Strings Reactjs

这就是我目前所做的

var longTextList = this.props.data.map(function(text, index){
                        return <Thumbnail key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });

既然returnreturns一个字符串,为什么我们不能用用户定义的字符串替换class名称呢。

例如 <Thumbnail><{this.props.type> 其中 this.props.type=Thumbnail.

编辑

我这样称呼我的 class

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type="Thumbnail"/>

其中类型告诉我们呈现缩略图。

在CardView.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Thumbnail } from 'react-bootstrap';


const CardView = React.createClass({


    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
var longTextList = this.props.data.map(function(text, index){
                        return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });


        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;

面临错误

Expected corresponding JSX closing tag for <Type> 

您可以用字符串替换 class 名称,只要该字符串以大写字母开头即可。组件首字母大写是 JSX 标准。区分标准 HTML 标签和表示组件的自定义标签很有用。阅读更多关于点符号的信息:tags vs react components

因此,例如,您可以使用点符号:<MyVar.mytype/>

如果使用文本变量"Tumbnail"动态定义组件类型,则必须在字典中引用与组件类型相关的组件。否则,转译将无法猜测要使用哪个组件。

你必须做到:

在文件名中MyComponent.js:

import { Thumbnail } from 'react-bootstrap';
const MyComponents={
  Thumbnail
};
export default MyComponents;

在你的 React 组件中,导入 MyComponent 和:

var Type = MyComponents[this.props.type];
return <Type/>;

你能绕过字符串,只传递类型作为 prop 吗?

import { Thumbnail } from 'react-bootstrap';

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type={Thumbnail}/>

现在 CardView.js

import React from 'react';
import ReactDOM from 'react-dom';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
        var longTextList = this.props.data.map(function(text, index){
                               return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Type>;
                           });

        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;