Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

reactjs - styled-components with custom React components: passing props

I have a custom component that takes in a property icon and sets the button's inner image to the corresponding icon as follows:

<custom-button-icon ref={showIcon} slot="right" icon="tier1:visibility-show" onClick={() => isPasswordVisible(false)} />

I would like to apply custom styling to a couple of instances of this component using styled-components. How can I pass the icon prop in so that it still functions (gets passed in as a pop of custom-button-icon)? This is what I have so far but it returns an empty button (with no icon):

export const d2lButtonIcon = ({ icon }) => {
  const buttonIcon = styled(`d2l-button-icon`)`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 100px;
    margin: 1px;
`
  return <buttonIcon icon={icon} />
}

Thanks!

question from:https://stackoverflow.com/questions/65926173/styled-components-with-custom-react-components-passing-props

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a really unusually case because this d2l-button-icon that you are dealing with a custom HTML element rather than a React component.

styled-components can style any React component and any built-in DOM element (a, div, etc.), but I don't think it knows how to deal with a custom DOM element because that's just not the way that we build things in React.

At first I tried passing the style to the d2l-button-icon element, and I got the icon prop to pass through but the style was ignored.

The way that I got this to work is to apply the styles to a div around the element and pass the other props to the d2l-button-icon element itself.

// function component adds styles around the icon button
const UnstyledD2L = ({ className, ...props }) => {
  return (
    <div className={className}>
      <d2l-button-icon {...props} />
    </div>
  );
};

// can use styled-component to style this wrapper component
const StyledButtonIcon = styled(UnstyledD2L)`
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100px;
  margin: 1px;
`;

// example usage with props
export default () => <StyledButtonIcon text="My Button" icon="tier1:gear" />;

However if you aren't super attached to this Brightspace package, I would recommend switching to a UI library that is designed for React.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...