简体   繁体   中英

Create dynamic tags with Styled Components

Is there a way to create a dynamic tag using styled-components? For example:

const MyComponent = styled(CustomTag)``;

<MyComponent element="h1" />

You can use as prop by default on components created with styled-components. If in your example CustomTag is also a styled-component that styles a native element (eg:)

const CustomTag = styled.h1`
  color: red;
`;

then you can do

const MyComponent = styled(CustomTag)`
  font-size: 64px;
`;

<MyComponent as="span">Something</MyComponent>

and you'll end up with a <span> tag with font-size of 64px and red text color. Of course you can also use as prop on CustomTag so you don't necessarily need MyComponent .

Maybe this will help you:

Add you code in your typescript

class Test extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<h1>Hello World...</h1>`;
        this.style.color = "red";
    }
}

customElements.define('test', Test);

after compiling refer the js file in you HTML and you can use it like <test></test>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM