动态渲染React组件 [英] Dynamically Rendering a React component

查看:112
本文介绍了动态渲染React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React JSX中似乎无法做到这样的事情:

In React JSX it does not appear to be possible to do something like this:

render: function() {
  return (
    <{this.props.component.slug} className='text'>
      {this.props.component.value}
    </{this.props.component.slug}>
  );
}


我得到一个解析错误:意外的令牌{。这不是React
可以处理的吗?

I get a parse error: Unexpected token {. Is this not something React can handle?

我正在设计这个组件,以便在引擎盖下存储值在 this.props.component.slug 将包含有效的HTML元素(h1,p等)。有没有办法让这个工作?

I'm designing this component so that under the hood, the values stored in this.props.component.slug will contain valid HTML elements (h1, p, etc.). Is there any way to make this work?

推荐答案

你不应该把组件slug放在花括号中:

You should not put component slug in curly braces:

var Hello = React.createClass({
    render: function() {
        return <this.props.component.slug className='text'>
            {this.props.component.value}
        </this.props.component.slug>;
    }
});

React.renderComponent(<Hello component={{slug:React.DOM.div, value:'This is my header'}} />, document.body);

这是一个工作小提琴: http://jsfiddle.net/kb3gN/6668/

Here is a working fiddle: http://jsfiddle.net/kb3gN/6668/

此外,您可以找到JSX Compiler对调试这类错误很有帮助:
http://facebook.github.io/react/jsx-compiler.html

Also, you can find JSX Compiler helpful for debugging these kind of errors: http://facebook.github.io/react/jsx-compiler.html

这篇关于动态渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆