【问题标题】:Condition inside render method in reactjsreactjs中渲染方法内部的条件
【发布时间】:2020-06-25 16:22:51
【问题描述】:
  • 我是新手。
  • 我遇到了语法错误,你们能告诉我如何解决它吗?
  • 在下面提供我的代码。 如果条件,我是否缺少任何括号
./src/views/view.jsx
Module build failed: SyntaxError: C:/workspace//src/views/view.jsx: Unexpected token (129:41)
  127 | 
  128 | 
> 129 |                                          if(this.props.playerInfo.fundingDetailId === null)
      |                                          ^
  130 |                                         {
  131 |                                         <div>
  132 |                                             <a className="closeButton" onclick={this.hidePopover}>Close</a>
import React, {Component} from 'react';
import {connect} from 'react-redux';
import SportsBody from '../../components/scores/tracker/score-tracker-ira';
import Player from '../../components/player/snapshot/player-snapshot-presenter-ira';
import {setSidebarAppMode} from 'sports-template-standard/lib/redux/layout/layout-actions';
import {updateMenu} from '../../redux/menu/menu-actions';
import {Overlay} from 'sports-modal';
import SportsDefect from 'sports-logger';
import {version} from '../../../package.json';



const sportsDefect = new SportsDefect();

class KickIra extends Component {
    constructor(props) {
        super(props);

        this.state = {popoverIsActive: true};

        this.launchGoalDetails = this.launchGoalDetails.bind(this);
        this.hidePopover = this.hidePopover.bind(this);
        this.sportsFollow = this.sportsFollow.bind(this);
    }

    componentDidMount() {
        sportsDefect.log('IRA Rollover Kick View Loaded  Ver:' + version);
    }

    launchGoalDetails() {
        this.props.dispatch(setSidebarAppMode(true));
        this.props.dispatch(updateMenu('score-details'));
        window.scrollTo(0, 0);
    }

    **hidePopover() {
        console.log("insidePopup")
        debugger;
        this.setState({popoverIsActive: false});
    }**

    sportsFollow() {
        const urlToLaunch = `/inet/iraRollover/IraRollOver/InvRolloverLandingPage?fundId=${this.props.playerInfo.fundingDetailId}`;
        window.open(urlToLaunch, '_self');
    }

    getHeaderContent() {
        const {profile} = this.props;

        return (
            <span>
                <div className="title">WELCOME{profile && profile.firstName && `, ${profile.firstName}`}!</div>
                <div className="subTitle">Digital Investment Adviser</div>
            </span>
        );
    }

    static basketballContent() {
        return (
            <p>
                If you want to know more about the status of your IRA Rollover, use the link below
                to visit the IRA Rollover Tracker on our website.
            </p>       
        );
    }

    /*static basketballContentNoChange() {
        console.log("inside  basketballContentNoChange---->");
        return (
            <div></div>
        );
    }*/

    static popupFooter() {
        //debugger;
        /*return (
            <div>
                <a className="closeButton" href="javascript:;" onClick={this.hidePopover}>Close</a>
                <a className="iraRollover sports-modal-trigger" href="javascript:;" onClick={this.sportsFollow}>Check Out IRA Rollover Tracker</a> 
            </div>       
        );*/
    }

    /*static popupFooterClose() {
        return (
            <a className="closeButton" href="javascript:;" onClick={this.hidePopover}>Close</a>
        );
    }*/

    render() {

        //console.log("summary-ira this.props.playerInfo.fundingDetailId ---->" + this.props.playerInfo.fundingDetailId);
        //debugger;

        /*if(this.props.playerInfo.fundingDetailId === undefined || this.props.playerInfo.fundingDetailId === '' ) {

        }*/
        return (
            <span>
                <section className="gray-box snapshotContainer">
                    <div className="flex-container flex-2">
                        <div className="snapshot flex-item">
                            <Overlay
                                className="popover--IRA"
                                active={this.state.popoverIsActive}
                                headerTitle={this.getHeaderContent()}
                                enableCloseShortcuts={true}
                                maxWidth={800}
                                onClose={this.hidePopover}
                            >
                                <div className="dia-popover-content level1">
                                    <p>
                                        As you requested, we are in the process of rolling over the balance from your qualified plan to your new IRA.
                                    </p>
                                </div>
                                <div className="dia-popover-content level2 dia-text-center">
                                    <p>
                                        Feel free to take a look around your new dashboard; this is where we'll show you what's
                                        happening with your new investment player.
                                    </p>
                                    <p>
                                        There isn't much to display yet, so don't let that concern you.
                                    </p>




                                    {/*(this.props.playerInfo.functionDetailId !== null ||
                                 this.props.playerInfo.fundingDetailId !== '' ||
                                  this.props.playerInfo.fundingDetailId !== undefined ) && 
                                   SummaryIra.rolloverContent()*/


                                     if(this.props.playerInfo.fundingDetailId === null)
                                    {
                                    <div>
                                        <a className="closeButton" onclick={this.hidePopover}>Close</a>
                                        <a className="iraRollover usaa-modal-trigger" href="javascript:;" onClick={this.openIRATracker}>Check Out IRA Rollover Tracker</a> 
                                    </div>  
                                    }  
                                }


                                </div>
                                <div className="dia-popover-content level3">

                                    {
                                        this.props.playerInfo.fundingDetailId === null || this.props.playerInfo.fundingDetailId === '' || this.props.playerInfo.fundingDetailId === undefined ?
                                            KickIra.popupFooterClose() :
                                            KickIra.popupFooter()
                                    }

                                </div>
                            </Overlay>
                            <SportsBody />
                        </div>

                        <div className="snapshot flex-item">
                            <Player />
                        </div>
                    </div>
                </section>
            </span>
        );
    }
}

KickIra.propTypes = {
    playerInfo: React.PropTypes.object,
    scoreDetails: React.PropTypes.object,
    profile: React.PropTypes.object
};

export default connect(state => ({
    scoreDetails: state.scoreDetails,
    playerInfo: state.player,
    profile: state.template.profile
}))(KickIra);

【问题讨论】:

    标签: javascript html css reactjs redux


    【解决方案1】:

    你不能在 JSX 中使用 if-else,如果你想设置一些条件,那么使用 ternary operator 或使用 functions(在需要检查许多条件时很有帮助,它使代码更具可读性)。

    使用三元运算符:

    <div>{1==1 ? 'Hello World' : null}</div>
    

    使用功能:

    <div>{this.checkCondition()}</div>
    
    checkCondition(){
    
        if(1==1){
            return 'Hello World'
        }else{
            return null;
        }
    
    }
    

    检查fiddle上的示例工作代码:https://jsfiddle.net/sgLywd6m/

    参考:http://reactjs.cn/react/tips/if-else-in-JSX.html

    查看这篇关于 react 类中的静态方法的文章:http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx

    【讨论】:

    • 感谢您的回复...但是如果我使用三元运算符,我遇到了这个问题,您能帮忙吗stackoverflow.com/questions/42358231/…
    • 创建了一个示例代码,它的工作,它应该也适用于你的情况,顺便说一句,哪个锚不工作closecheckout Ira.... ??
    • 你的代码在小提琴中工作,我提到静态会有问题....这个不工作 -----> 关闭
    • 不工作意味着什么???你得到任何错误或控制台没有打印任何东西,因为我在小提琴和示例项目中使用了相同的代码,两者都正常工作。
    • 它没有调用这个函数 hidePopover,所以我无法关闭弹出窗口...我已将弹出窗口的内容放入静态函数中,它是否因此无法正常工作
    【解决方案2】:

    您的 JSX 中不能有 if 语句,在此处了解如何进行条件渲染:http://reactjs.cn/react/tips/if-else-in-JSX.html

    【讨论】:

    【解决方案3】:

    您可以使用三元运算符对条件进行编码。 在你的情况下,

     {
      this.props.playerInfo.fundingDetailId === null) ? 
       <div>
        <a className="closeButton" onclick={this.hidePopover}>Close</a>
        <a className="iraRollover usaa-modal-trigger" href="javascript:;" 
            onClick={this.openIRATracker}>
        Check Out IRA Rollover Tracker
        </a>
       </div>
    : 'here else part'
    }
    

    对于锚标记的 onClick 方法问题。 还是这样吧,

    onClick={() => {this.setState({var:'value'}) }}
    

    或者 在构造函数中绑定方法。喜欢

    this.method = this.method.bind(this)
    

    【讨论】:

      【解决方案4】:

      创建您自己的 IF 组件以在 JSX 中使用:

      定义

      import React from 'react';
      
      export class IF extends React.Component {
      
          render(){
              let lookFor = this.props.condition ? THEN : ELSE;
              let children = this.props.children;
              if(Array.isArray(children)){
                  children = children.filter((child) => child.type === lookFor)
              } else if(children.type !== lookFor){
                  children = null;
              }
              return children;
          }
      }
      
      export class THEN extends React.Component {
          render(){
              return this.props.children;
          }
      }
      
      export class ELSE extends React.Component {
          render(){
              return this.props.children || null;
          }
      }
      

      用法:

      render(){ return (
      <div>
        doSomething
      
        <IF condition={this.state.something === true}>
          <THEN>
            <div> is shown only if condition equals true </div>
          </THEN>
          <ELSE>
            <div> is shown only if condition equals false. ELSE can be omitted.
          </ELSE>
        </IF>
      
        doMore
      </div>
      );}
      

      【讨论】:

        【解决方案5】:

        在 JSX 中你可以使用:

        <div>
          {(() => {
            if(this.something){
              return <span>something</span>
            } else {
              return "nothing to see here";
          })()}
        </div>
        

        或者如果您不需要“this”关键字。

        <div>
          {function() {
            if(something){
              return <span>something</span>
            } else {
              return "nothing to see here";
          }()}
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-20
          • 1970-01-01
          • 2019-11-30
          相关资源
          最近更新 更多