如何使用标记的模板文字获取子样式组件中父组件的状态?

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

我有一个反应组件 App 如下,它有一个状态 WHRatio,我的 div 组件将使用 WHRatio 值来计算 height 值。按照我下面的方式,是可以的,可以成功获取到父组件状态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;
`

我想使用标记的模板文字来设置我的组件的样式而不是内联样式。那么如何使用标记的模板文字获取子样式组件中父组件的状态?

Online Demo

您可以通过将道具值传递给自定义样式来做到这一点,例如:

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.

示例 2:

import styled, { css, keyframes } from 'styled-components'

const animation = keyframes`
  0% {
    opacity: 0;
  }

  100 {
    opacity: 1;
  }
`

const animationRule = css`
  ${animation} 1s infinite alternate;
`

const Component = styled.div`
  animation: ${animationRule};
`

DEMO URL

你试过这样的吗:

你传递你的 sizeWidth 就像

<Container sizeWidth={sizeWidth}/>

然后在您的样式组件中将像:

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