通过 Object 映射作为 props 传递给 child

Mapping through Object that is passed to child as props

我正在尝试通过作为道具传递的 object 进行映射,并希望为不同的 object 值显示不同的 HTML 元素

Object;

         const allDesc =  {description: "Title Description", description1: "Intro 
    Description", description3:"Sub title", description3: "Sub Description"}

代码:

      <div>
        {Object.keys(allDesc).map((desc, index) => {
          if (allDes[desc] !== "") {
            return (
              <>
                <h1>allDesc.description</h1>
                <p>allDesc.description1</p>
                <h3>allDesc.description2</h3>
                <p>allDesc.description3</p>
              </>
            );
          }
        })}
      </div>

此方法不显示任何内容,通过 object 进行映射并为不同的 object 值显示不同的 HTML 元素的正确方法是什么。谢谢!

请试试这个。

<div>
        {Object.keys(allDesc).map((desc, index) => {
          if (allDes[desc] !== "") {
            return (
              <>
                {
                 desc === 'description' ? <h1>allDes[desc]</h1> : 
                 <p>allDes[desc]</p>
                } 
              </>
            );
          }
        })}
      </div>

allDes[desc] 具有您从对象键循环的所有字段的值。

map 超过 Object.entries。如果键匹配“描述” return 值作为 <h1>,否则 return 值作为 <p>.

function Example({ allDesc }) {
  return (
    <div>
      {Object.entries(allDesc).map(([key, value]) => {
        if (key === 'description') return <h1>{value}</h1>;
        if (key === 'description3') return <h3>{value}</h3>;
        return <p>{value}</p>;
      })}
    </div>
  );
};

const allDesc = {description: 'Title Description', description1: 'Intro Description', description3: 'Another Description', description4: 'More text' };

ReactDOM.render(
  <Example allDesc={allDesc} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>