简体   繁体   中英

How do I go about making a re-usable button in svelte?

I would like to make a re-usable button component where I can change the color for instance. Let's say I have a base button but I want to override some properties (could be more than the background color. Ideas?

//Button.svelte
<script>
    export let backgroundColor;
</script>

<style>
 button {
   padding: 15px 20px;
   margin: 10px;
   background-color: #9174eb;  <-- I want this to be dynamic
   color: white;
   border-radius: 15px;
   box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
 }

 button:hover {
  background-color: #A78BFA; <-- This as well, and if possible based on the backgroundColor value (i don't want to use sass or anything like that) 
 }
</style>


<button style="background-color : {backgroundColor}" on:click on:mouseover>
  <slot></slot>
</button>

style="background-color: {backgroundColor}" has its limitations, for instance I cannot target the hover. And with svelte we can't inject js variables in the stylesheets...

I like to use CSS custom properties for this.

<!-- Button.svelte -->
<script>
    export let backgroundColor;
</script>

<style>
    button {
        background-color: var(--backgroundColor);
    }
    
    button:hover {
        filter: brightness(95%);
    }
</style>

<button style="--backgroundColor: {backgroundColor}">
    <slot></slot>
</button>

This component can be used like so.

<script>
    import Button from './Button.svelte';
</script>

<Button backgroundColor="lightgreen">
    Button
</Button>
<Button backgroundColor="#ffaaff">
    Button
</Button>
<Button backgroundColor="hsla(170, 45%, 45%, 1)">
    Button
</Button>

A proposed Svelte feature will make this easier.

I apply a CSS filter on hover so the hover color is slightly darker than the background color. See this Stack Overflow answer for some other pure CSS options.

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