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

Write javascript commands on a render() component method

我正在尝试 return 一个 HTML 元素或另一个元素,具体取决于在 Javascript 上计算的某些条件。我试过这样做,但我不能以 if 开始条件,我不明白为什么。 我的组件文件是这个:

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>
        );
    }

有人发现问题吗?

您不能在 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>;
  }));
}

您不能在 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

在 ReactJS 的组件 (JSX) 中,除了 returns 一个值的声明之外,你不能使用任何其他东西。

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

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 ) }
   )
}