簡體   English   中英

在 React 中使用 props 傳遞數據的最佳實踐

[英]best practices in passing data with props in react

我的項目結構有問題,我想知道解決問題的最佳方法是什么。 我有三個組件和兩層嵌套:

我的祖父組件:

function WhatClientSay() {
 
  return (
    <Container
      component="section"
    >
      <ClientCard />
    </Container>
  );
}

ClientCard組件:

import ClientAvatar from "../ClientAvatar/ClientAvatar";

function ClientCard(props) {
  return (
    <div>
      <Box>
        <Typography
          fontWeight="600"
        >
          what client say
        </Typography>


        <Typography>
          “Excepteur sin occaecat cupidatat proident. It’s sunt in culpa qui
          officia deserunt mollit anim id 
        </Typography>

        <Box sx={{ display: "grid", placeItems: "center" }}>
          <ClientAvatar
            username="naomi hamilton"
            role="customer"
            rate={5}
            profileImg={profileImg}
          />
        </Box>
      </Box>
    </div>
  );
}

和我的ClientAvatar組件(它只是在照片旁邊呈現一些道具作為頭像):

function ClientAvatar({ profileImg, username, role, rate }: AvatarProps) {
  return (
    <>
      <Box sx={{ mt: 3, "& img": { width: 70, height: 70 } }}>
        <Grid container spacing={1}>
          <Grid item>
            <img src={profileImg} alt="profile" />
          </Grid>
          <Grid item>
            <Grid
              container
              direction="column"
              spacing={0}
              justifyContent="space-between"
              alignItems="flex-start"
            >
              <Grid item>
                <Typography
                  sx={{
                    fontSize: 15,
                    textTransform: "uppercase",
                    fontWeight: "600",
                  }}
                >
                  {username}
                </Typography>
              </Grid>
              <Grid item>
                <Typography
                  sx={{
                    fontSize: 13,
                    textTransform: "uppercase",
                    fontWeight: "600",
                    mb: 1,
                  }}
                >
                  {role}
                </Typography>
              </Grid>
              <Grid item>
                <Rating size="small" name="read-only" value={rate} readOnly />
              </Grid>
            </Grid>
          </Grid>
        </Grid>
      </Box>
    </>
  );

所以我的問題是:

  1. 將數據傳遞到我的組件的最佳方式是什么? 我應該將 ClientAvatar 道具從祖父母組件傳遞給孩子,然后再傳遞給它的孩子嗎?

  2. 編寫標題和副標題等硬編碼值的最佳方式是什么? 我應該將它們存儲在 object 中並將它們作為道具傳遞給子組件嗎? 或者我應該像這樣制作一個 object 並將其傳遞給排版?

const contexts = {title : 'what client say' , subtitle:' lorem lorem' }

提前致謝。

  1. 這取決於您的 ClientAvatar 道具的來源。 我的意思是,如果您從祖父那里獲取這些數據,那么是的,您可以從該級別開始鑽取,否則如果數據來自 ClientCard 組件,那么您的祖父組件不應該知道它。
  2. 我更願意將它們作為字符串傳遞,因為如果您使用 object,那么您可能不需要子組件中 object 的所有屬性,但您無論如何都會無緣無故地發送它們,這會影響性能壞方法。 但這實際上取決於用例,在某些情況下使用 object 可能是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM