简体   繁体   English

有条件地呈现属性对象值?

[英]Conditionally render property object value?

I have this example function below:我在下面有这个示例函数:

const HelloWorld = (person, message) => {
      const { sender, message } = message
      const greeting = {
          to: person
          message: `Hi, ${sender} greets you. ${message}`
      };
      return sendMessage(greeting)
}

It works perfectly fine however message shows null if there's no value.它工作得很好,但是如果没有值,则消息显示为null How can I conditionally render values.如何有条件地呈现值。 {message === null : Hi, ${sender} greets you. {message === null : Hi, ${sender} greets you. : Hi, ${sender} greets you. He said ${message} Hi, ${sender} greets you. He said ${message} Hi, ${sender} greets you. He said ${message} } Hi, ${sender} greets you. He said ${message} }

 const HelloWorld = (person, message) => { const { sender, msg } = message const greeting = { to: person, message: `Hi, ${sender} greets you.${msg ? 'He said '+ msg : ''}` }; return greeting; // return sendMessage(greeting); } console.log(HelloWorld('Jack', { sender: "Joe", msg: "Test MSG" })); console.log(HelloWorld('Jack', { sender: "Joe", msg: "" }));

You can simply use a ternary inside the string interpolation.您可以简单地在字符串插值中使用三元。

You can use the ternary operator inside the template string, also note template strings can be nested:您可以在模板字符串中使用三元运算符,还要注意模板字符串可以嵌套:

 const HelloWorld = (person, msg) => { const { sender, message } = msg; const greeting = { to: person, message: `Hi, ${sender} greets you.${message ? ` He said ${message}`: ""}` }; return greeting } console.log(HelloWorld("John Doe", {sender: "Jane Doe", message: null})); console.log(HelloWorld("John Doe", {sender: "Jane Doe", message: "Howdy"}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有条件地更改 object 属性 - Conditionally change object property 有条件地设置对象属性 - Conditionally set a object property 有条件地设置对象属性 - Conditionally set an object property 如何在JS中以更好的方式有条件地更改对象属性值? - How to conditionally change object property value in the better way then this solution in JS? 有条件地将变量的值分配给对象的属性,该属性可以为null - Conditionally assign the value of a variable to an object's property that may be null 如何检查对象属性是否存在,并有条件地分配默认值(在JavaScript中) - How to check if an object property exists, and conditionally assign default value (in JavaScript) 有条件地分配对象值? - assign an object value conditionally? 如何有条件地渲染映射数组中的映射对象 - How conditionally render mapped object in mapped array 如果 object 属性值符合某些条件,如何在反应中呈现数据? - How to render data in react if object property value match certain criteria? 如果 object 不为空,我如何有条件地渲染 object 以显示一段代码,如果 object 有 key: value 则显示一段代码 - How do I conditionally render an object to display one section of code if the object is not empty and one section of code if the object has key: value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM