簡體   English   中英

如何使用標記的模板文字在子樣式組件中獲取父組件的 state?

[英]How do I get the state of the parent component in a child styled component using tagged template literals?

我有一個如下的反應組件App ,它有一個 state WHRatio ,我的div組件將使用WHRatio值來計算height值。 按照我下面的方式,它可以工作,它可以成功獲取父組件state WHRatio

import React, { useState } from "react";

export default function App() {
  const sizeWidth = 100;
  const [WHRatio, setWHRatio] = useState(1);

  const getContainerHeight = () => Math.floor(sizeWidth / WHRatio);

  const incWHRatio = () => setWHRatio(WHRatio + 1);

  return (
    <>
      <div
        style={{
          width: sizeWidth,
          height: getContainerHeight(),
          backgroundColor: "orange"
        }}
      >
      </div>
      <button onClick={incWHRatio}>Inc WHRatio</button>
    </>
  );
}

眾所周知, styled-components使用標記的模板文字來設置組件的樣式。

// something like this
const Container = styled.div`
  background-color: orange;
  width: 100px;
  height: 200px;
`

我想使用標記的模板文字來設置我的組件的樣式而不是內聯樣式。 那么如何使用標記模板文字在子樣式組件中獲取父組件的 state 呢?

在線演示

您可以通過將 props 值傳遞給自定義樣式來做到這一點,例如:

const Container = styled.div`
  background-color: orange;
  width: 100px;
  height: ${props => props.customHeight + "px"}
`

完整示例:

import React, { useState } from "react";
import styled from "styled-components";

const Container = styled.div`
  background-color: orange;
  width: 100px;
  height: ${props => props.customHeight + "px"}
`

export default function App() {
  const sizeWidth = 100;
  const [WHRatio, setWHRatio] = useState(1);

  const getContainerHeight = () => Math.floor(sizeWidth / WHRatio);

  const incWHRatio = () => setWHRatio(WHRatio + 1);

  return (
    <>
      <Container
        customHeight={getContainerHeight()} 
      ></Container>
      <button onClick={incWHRatio}>Inc WHRatio</button>
    </>
  );
}

此外,您可以使用 css 功能並將其傳遞給樣式組件,有關更多詳細信息和示例,您可以查看此url

演示 URL

你有沒有嘗試過這樣的:

你通過你的 sizeWidth 像

<Container sizeWidth={sizeWidth}/>

然后在您的樣式組件中將如下所示:

const Container = styled.div`
  width: ${(props) => props.sizeWidth + "px"};
`

暫無
暫無

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

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