简体   繁体   English

React - 如何为地图功能的每个元素设置内联 CSS?

[英]React - how to set inline CSS for each element of map function?

I have an application in React where I'm trying to read in data from a JSON file.我在 React 中有一个应用程序,我试图从 JSON 文件中读取数据。 The JSON file is in the following format: JSON 文件采用以下格式:

[
    {
        "name": "Max",
        "age": "21",
    },

    {
        "name": "Sam",
        "age": "18",
    }

    ........
]

I have successfully read in the right data and displayed it on my screen, like this:我已成功读入正确的数据并将其显示在我的屏幕上,如下所示:

function foo(){
    const styling = css`
        font-size: 30px;
    `;

    return(
        <div>
            {people.map((person, i) => <Format key={i} {...person} css={styling}/>)}
        </div>
    );
}

Although all the information correctly displays on the screen, the styling is not getting applied to each person.尽管所有信息都正确显示在屏幕上,但样式并未应用于每个人。 How could I change this?我怎么能改变这个?

EDIT编辑

Format component:格式组件:

function Format({name, age}){
   return (
      <div>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}
function Format({name, age, css}){
   return (
      <div css={css}>
         <h1>{name}</h1>
         <h2>{age}</h2>
      </div>
   );
}

you passed styled to your component but you didnt use them in your child component您将样式传递给您的组件,但您没有在子组件中使用它们

and plus using idx as key is not the best practice.加上使用 idx 作为关键不是最佳实践。 following article explains why.下面的文章解释了原因。 https://reactjs.org/docs/lists-and-keys.html https://reactjs.org/docs/lists-and-keys.html

if name is unique you can pass each items name to mapped children.如果名称是唯一的,您可以将每个项目名称传递给映射的子项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM