根据它们的 id 是奇数还是偶数进行交替 React

发布于 2025-01-15 09:28:45 字数 437 浏览 3 评论 0原文

我正在将 React 用于网页。在组件中,左侧有一个 div,右侧有一个图像。

我希望它们根据它们的 id 是奇数还是偶数来交替。

function Item({ title, text, link, img,id }) {
  return (
    <div >
      <div>
        <h3>
          {title}
        </h3>
        <p>{text}</p>
        <a href={link}>
          text
        </a>
      </div>
      <img src={img} alt={title} />
    </div>
  );
}

I am using React for a web page. In a component, I have a div on the left and an image on the right.

I would like them to alternate depending on whether their id is odd or even.

function Item({ title, text, link, img,id }) {
  return (
    <div >
      <div>
        <h3>
          {title}
        </h3>
        <p>{text}</p>
        <a href={link}>
          text
        </a>
      </div>
      <img src={img} alt={title} />
    </div>
  );
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贩梦商人 2025-01-22 09:28:45

将 div 转换为组件,并按照您想要的顺序有条件地渲染它们:

function Item(props) {
  return (
    props.id % 2 == 0 ? 
    <div >
      <Div {...props} />
      <img src={img} alt={title} />
    </div>
    :
    <div >
      <img src={img} alt={title} />
      <Div {...props} />
    </div>
  );
}


const Div = ({ title, text, link }) => (
  <div>
    <h3>
      {title}
    </h3>
    <p>{text}</p>
    <a href={link}>
      text
    </a>
  </div>
)

Turn the div into a component and conditionally render them in the order you want:

function Item(props) {
  return (
    props.id % 2 == 0 ? 
    <div >
      <Div {...props} />
      <img src={img} alt={title} />
    </div>
    :
    <div >
      <img src={img} alt={title} />
      <Div {...props} />
    </div>
  );
}


const Div = ({ title, text, link }) => (
  <div>
    <h3>
      {title}
    </h3>
    <p>{text}</p>
    <a href={link}>
      text
    </a>
  </div>
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文