React中的条件语句渲染方法

时间:2019-11-27 06:41:36

标签: reactjs conditional-statements

我是个新手,我正在尝试在render方法中添加一个条件,以便如果值framework1为空,则无需在HTML中添加文本。

下面是我的代码。

buildResults = () => {
 const {
results
} = this.state;

return {
  <div className={`${block}__results`}>
   <table>
    <thead></thead>
<tbody>
   { results.map(item => this.buildResult(item)) }
</tbody>
</table>

</div>
}


buildResult = (data) => {
  const {
   framework1,
   framework2
} = data;

return (
 <tr className={`${block}__row`}>
   <td className={`${block}__cell ${block}__cell--ticker`}>
/* I need to display the text "view" only if framework1 is not empty */
   <a href={`${framework1}`} target="_blank" rel="noopener noreferrer">View</a>
</td>
</tr>
)
}

1 个答案:

答案 0 :(得分:0)

使用if语句检查是否有数据,在这种情况下,我正在检查framework1中的数据是否为字符串。

buildResults = () => {
 const {
results
} = this.state;

return {
  <div className={`${block}__results`}>
   <table>
    <thead></thead>
<tbody>
   { results.map(item => this.buildResult(item)) }
</tbody>
</table>

</div>
}


buildResult = (data) => {
  const {
   framework1,
   framework2
} = data;

return (
 <tr className={`${block}__row`}>
   <td className={`${block}__cell ${block}__cell--ticker`}>
   if (framework1.indexOf("ST1") ){
     // display something else
   }
   else {
     <a href={`${framework1}`} target="_blank" rel="noopener noreferrer">View</a>
   }
</td>
</tr>
)
}