如何与三元运算符一起使用道具

时间:2019-03-29 20:03:35

标签: reactjs

我正在尝试在三元运算符中使用传递的prop,但是似乎无法使其正常工作。我提供的是代码示例,而不是实际的代码,但是我认为这可以捕获问题,而不必包含很长的代码。我想添加一个条件:如果props传递了=“ Good”,那么让该语句更改为“ that's a nice word”

       function Speak(props){

        return(

        <div>
        {props.word}==="Good" ? "that's a nice word" : 
"Its not nice to say"{props.word}
        </div>
        );





    function Speak(props){

    return(

    <div>
  // I want to add a condition
    It is not nice to say <strong>{props.word}</strong>!
    </div>
    );

我想添加一个条件:如果props传递了=“ good”,那么将语句更改为“ that is a nice word”

2 个答案:

答案 0 :(得分:0)

Yo可以这样说:

const Speak = (props) => {
  return(
    <div>
      {props.word === "Good" ? 
        <span>That's a nice word.</span> : 
        <span>It's not nice to say <b>{ props.word }</b>.</span>
      }
    </div>
  );
}

答案 1 :(得分:0)

您希望将条件逻辑放在方括号{ ... }中。

function Speak(props) {
    return (
        <div>
            {props.word === "Good"
                ? <span>That's a nice word!</span>
                : <span>It is not nice to say <strong>{props.word}</strong>!</span>
            }
        </div>
    )
}