【问题标题】:Render Array of JSX.Element OR HTMLElement React Typescript渲染 JSX.Element 数组或 HTMLElement React Typescript
【发布时间】:2020-02-01 23:25:56
【问题描述】:

我目前正在为自定义引导卡创建卡包装器。我正在努力做到这一点,以便开发人员可以根据需要在卡的正面和背面动态呈现元素。这就是我目前所拥有的

import React, { useState, ReactElement } from 'react';
import { Card, ListGroup } from 'react-bootstrap';

interface Side {
  imgSrc?: string;
  title?: string;
  text?: string;
  body?: (HTMLElement | JSX.Element)[];
}

interface CCardProps {
  className?: string;
  front?: Side;
  back?: Side
}

const CCard: React.FC<CCardProps> = ({ className, front = {}, back = front }) => {
  const [cardValue, setCardValue] = useState(front);

  return (
    <Card className={className || ''} onClick={() => cardValue === front ? setCardValue(back) : setCardValue(front)} style={{ width: "19rem", minHeight: '26rem' }}>
      {cardValue.imgSrc && <Card.Img style={{ maxHeight: '100%', maxWidth: '100%' }} variant="top" src={cardValue.imgSrc} />}
      <Card.Body>
        {cardValue.title && <Card.Title>{cardValue.title}</Card.Title>}
        {cardValue.text && <Card.Text>{cardValue.text}</Card.Text>}
        {cardValue.body && cardValue.body.length > 0 && cardValue.body.map((item, index) => 
          // What do I do here?
        }
      </Card.Body>
    </Card>
  )
};

export default CCard;
// Example use
<CCard 
  front={{
    imageUrl: 'cutePuppyPhoto',
    body: [
      <a href="#">Click me!</a>,
    ]
  }}
  back={{
    title: 'This is a title',
    text: 'This is some text',
    body: [
      <Card.Text>Hello There</Card.Text>
    ]
  }}
/>

cardValue.body 既可以是 HTML 元素 &lt;a&gt; or &lt;h1&gt; 等,也可以是其他 JSX 元素(如果我想输入 &lt;Card.Text&gt; 或其他东西。我现在不知道如何动态映射这两个 一个键。任何帮助将不胜感激。

【问题讨论】:

  • {cardValue.body} 不起作用吗?
  • 将密钥放入CCard.body初始化
  • 出于某种原因{cardValue.body} 有时对我大喊大叫,有时却没有。我很困惑。

标签: javascript reactjs typescript jsx tsx


【解决方案1】:

原来我很笨,数组已经填充了 elements 而不是值,所以我不需要地图。

<Card className={className} onClick={() => cardValue === front ? setCardValue(back) : setCardValue(front)} style={{ width: "19rem", minHeight: '26rem' }}>
  {cardValue.imgSrc && <Card.Img style={{ maxHeight: '100%', maxWidth: '100%' }} variant="top" src={cardValue.imgSrc} />}
  <Card.Body>
    {cardValue.title && <Card.Title>{cardValue.title}</Card.Title>}
    {cardValue.text && <Card.Text>{cardValue.text}</Card.Text>}
    {cardValue.body}
  </Card.Body>
</Card>

映射值,而不是子元素

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 2020-09-18
    • 1970-01-01
    • 2018-03-24
    • 2021-03-30
    • 1970-01-01
    • 2021-10-30
    • 2022-07-04
    • 2018-06-16
    相关资源
    最近更新 更多