React Styled-Components传递道具问题

时间:2019-05-21 06:25:41

标签: reactjs styled-components

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

下面是我编写的代码

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,它将正常工作。

1 个答案:

答案 0 :(得分:0)

出于某些奇怪的原因,道具没有传递到StyledComponent上,而是直接说明了我想要的东西。

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