简体   繁体   English

正确的方法(如果可能的话)将JSX代码存储到Javascript变量中

[英]Correct way (if possible) to store JSX code into a Javascript variable

I´ve written the following code using ReactJs´s JSX syntax: 我使用ReactJs´s JSX语法编写了以下代码:

import { Link } from 'react-router';

class SidebarMenuItem extends React.Component {

render() {

    var href = (this.props.submenu ? 'javascript:' : {<Link to="mod/admin" + this.props.link />};

    return ( 

        <a href={href} onClick={this.selected}>
            <i className={'fa ' + this.props.icon} />
            <span>{this.props.title}</span>
        </a>

    )
  }
}

But it seend that I cannot store a direct JSX code into a variable, as I got the following error: 但它发现我无法将直接JSX代码存储到变量中,因为我收到以下错误:

Module build failed: SyntaxError: D:/9. DEV/client/components/App/SidebarMenuItem.js: Unexpected token, expected , (41:52)

  40 | 
> 41 |      var href = (this.props.submenu ? 'javascript:' : {<Link to="mod/admin" + this.props.link />};
     |                                                        ^

What is the correct way to store my Link component in the href variable ? 将链接组件存储在href变量中的正确方法是什么?

你只需编写普通的jsx,在你的情况下你需要删除jsx周围的括号,然后在“mod / admin”+ this.props.link部分周围包括括号,就像你在render方法中写一样。

var href = this.props.submenu ? 'javascript:' : <Link to={"mod/admin" + this.props.link} />

在JSX周围使用()跨越多行

var href = this.props.submenu ? 'javascript:' : (<Link to="mod/admin" + this.props.link />);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM