【问题标题】:React Styled-Components passing props issueReact Styled-Components 传递道具问题
【发布时间】:2019-10-07 11:48:23
【问题描述】:

尝试创建一个接受多个参数的嵌套组件,例如。按钮样式、文本样式和可能的图标。如果我直接渲染按钮,一切(传递道具)都可以正常工作。

下面是我写的代码

import React from "react";
import styled from "styled-components";
import _ from "lodash";
import { hexToRgb } from "../styles/helpers";
import * as MaterialIcons from "styled-icons/material";

const StyledButton = styled.button`
  text-align: center;
  border: ${props =>
    props.outline ? `1px solid ${props.outlineColor}` : "none"};
  background: ${props => (props.background ? props.background : "#000")};
  border-color: ${props =>
    props.outlineColor ? props.outlineColor : "transparent"};
  min-width: 120px;
  width: ${props => (props.width ? props.width : "auto")};
  min-height: 40px;
  border-radius: 25px;
  color: ${props => (props.color ? props.color : "#FFF")};
  transition: all ease 0.5s;
  &:hover {
    cursor: pointer;
    background: ${props =>
      props.background ? hexToRgb(props.background) : "#FFF"};
  }
`;

const StyledText = styled.span`
  font-size: 16px;
  font-weight: ${props => (props.fontWeight ? props.fontWeight : 400)};
`;

const StyledIcon = styled(MaterialIcons.Lock)`
  font-size: 15;
  padding: 10px;
`;

const Button = props => {
  let _icon = null;
  const { children, icon } = props;
  console.log("props", props);

  if (icon) {
    _icon = <StyledIcon size="48" title="Test icon" />;
  }

  console.log("StyledButton", StyledButton);

  return (
    <StyledButton>
      <StyledText>{children}</StyledText>
      {_icon}
    </StyledButton>
  );
};

export default Button;

如果我直接导​​出默认的 StyledButton 就可以了。

【问题讨论】:

  • 包装它们?包装代码在哪里?
  • 究竟是什么问题?
  • 无法直接访问props.outlineColor、props.color等

标签: reactjs styled-components


【解决方案1】:

由于某些奇怪的原因,props 没有传递到 StyledComponent,但是直接说明我想要的工作。

   return (
    <StyledButton
      outlineColor={outlineColor}
      background={background}
      width={width}
      color={color}
      outline={outline}
    >
      <StyledText>{children}</StyledText>
      {_icon}
    </StyledButton>
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2021-05-01
    • 1970-01-01
    • 2019-02-18
    • 2021-08-04
    • 2020-11-20
    相关资源
    最近更新 更多