如果条件如何在React中添加图标

时间:2019-02-16 13:03:30

标签: reactjs icons

所以我渲染了Todo {text}

我该如何在'li'中添加条件?

如果(已完成){ 呈现此}

else {渲染此}?

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
  </li>
)

1 个答案:

答案 0 :(得分:1)

您可以像使用textDecoration一样使用三元运算符。

示例

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? "line-through" : "none"
    }}
  >
    {text}
    {completed ? (
      <img src="https://picsum.photos/g/200/200/?random" />
    ) : (
      <img src="https://picsum.photos/200/200/?random" />
    )}
  </li>
);

ReactDOM.render(
  <Todo onClick={() => {}} completed text="Foo" />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>