【问题标题】:Styled components – accessing props from a parent样式化组件——从父级访问道具
【发布时间】:2022-01-18 17:40:21
【问题描述】:

我有一个组件Box,看起来像这样:

const Box = ({ className, country }) => {
  const status = myStatusFunction(country);
  return (
    <div className={className} status={status}>
      {country}
    </div>
  );
};

我想在我的视图中使用这个组件,但还要根据status 属性为其添加自定义样式,所以我的styled.js 看起来像这样:

import _Box from 'components/Box';

const Box = styled(_Box)`
  ${({ status }) => {
    if (status === 'available') {
      return css`
        background-color: green;
      `;
    }
    return css`
      background-color: red;
    `;
  }}
`

这里的问题是status 在这里是undefined,所以我的问题是——你能以某种方式访问​​status 属性吗?

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    由于 React 具有自上而下的数据流,这是不可能的。 我建议将status 变量作为Box 组件的道具,以遵循自上而下的数据流。

    自顶向下流的意思是信息只从父级流向子级。通过将 _Box 组件封装在 styled 函数中,您基本上可以使 _Box 成为新创建的样式 Box 的子组件。这意味着您在这种情况下正在尝试在父组件中收集子组件的信息。

    我希望这能回答你的问题:)

    【讨论】:

      【解决方案2】:
      import { Wrapper } from './styles.js';
      
      const Box = ({ className, country }) => {
        const status = myStatusFunction(country);
      
        return (
          <Wrapper className={className} status={status}>
            {country}
          </Wrapper>
        );
      };
      

      styles.js:

      
      export const Wrapper = styled.div`
        ${({ status }) => {
          if (status === 'available') {
            return css`
              background-color: green;
            `;
          }
          return css`
            background-color: red;
          `;
        }}
      `
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 2018-09-21
        • 2019-01-24
        • 2021-08-10
        相关资源
        最近更新 更多