首页 文章

在render()组件方法上编写javascript命令

提问于
浏览
1

我试图返回一个HTML元素或另一个,取决于在Javascript上计算的一些条件 . 我尝试过这样做,但我无法启动条件,如果,我不明白为什么 . 我的组件文件就是这个:

import React from 'react';
import defaultImage from './defaultImage.jpg';

export default class Game extends React.Component {
    render() {
        const image = this.props.question.attachment.url;
        const tips = this.props.question.tips;

        return (
            <div className="flexDisplay">
                <img src={image === (null || "") ? defaultImage : image} className="questionImage centerVertical" alt="Error loading, just read the question" />
                <div className="centerHorizontal centerVertical">
                    <h1>{this.props.question.question}</h1>
                    <h2 className="centerHorizontal">Pistas:</h2>   
                    {   
                        if(tips.length === 0){ //The problem comes here
                            return <div>No hay pistas disponibles</div>
                        }else{
                            tips.map((tip, i,) => {
                                return <div className="centerHorizontal" key={tip.toString()}>{i+1}. {tip}</div>;
                            })
                        }
                    }
                </div>
            </div>
        );
    }

有谁发现了这个问题?

3 回答

  • 2

    在ReactJS的组件(JSX)中,除了返回值的语句之外,不允许使用任何其他内容 .

    您可以通过尝试分配变量来想象逻辑:

    const result = if ( a ) { "b" } else { "c" } // won't work
    

    但另一方面,它会Ternary Operator .

    const result = a ? "b" : "c";
    

    因此,在您的情况下,有两种方法可以实现目标:

    { tips.length === 0 ? ( <div>No hay pistas disponibles</div> ) : (
         tips.map((tip, i) => ( 
             <div className="centerHorizontal" key={ tip.toString() }>{i+1}. {tip}</div>
         ) )
    ) }
    

    或者您可以在方法中简单地提取它

    renderTips( tips ) {
        if ( tips.length === 0 ) { return null; }
        return tips.map( ( tip, i ) => (
            <div className="centerHorizontal" key={ tip.toString() }>{i+1}. {tip}</div>
        );
    }
    
    render() {
       ...
       return (
           ...
           { this.renderTips( tips ) }
       )
    }
    
  • 4

    您不能在JSX语法中使用 if 语句 . 相反,您可以使用基本上完成相同操作的三元运算符:

    {
    tips.length === 0 ? 
      (<div>No hay pistas disponibles</div>)
    : (tips.map((tip, i,) => {
      return <div className="centerHorizontal" key={tip.toString()}>{i+1}. {tip}</div>;
      }));
    }
    
  • 2

    您无法在jsx中的内联条件语句中使用“if” . 但是,您可以使用三元语法:

    {   
        tips.length === 0 ? (
            return <div>No hay pistas disponibles</div>
        ) : (
            tips.map((tip, i,) => {
                return <div className="centerHorizontal" key={tip.toString()}>{i+1}. {tip}</div>;
            })
        )
    }
    

    您可以在此处阅读有关使用内联条件语句的更多信息:https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

相关问题