繁体   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