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

你。 提交于 2020-12-02 07:14:21

问题


I´ve written the following code using ReactJs´s JSX syntax:

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:

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 ?


回答1:


you would just write plain jsx, in your case you need to remove the brackets around the jsx, and then include the brackets around the "mod/admin" + this.props.link portion just like you would when you write in the render method.

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



回答2:


Use () around JSX that spans multiple lines

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


来源:https://stackoverflow.com/questions/41947071/correct-way-if-possible-to-store-jsx-code-into-a-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!