我正在使用svelte进行免费代码训练营的“随机报价机”项目 这里 : https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine
我尝试对报价组件进行“比例”转换。过渡仅在第一次工作。我知道我需要每次创建和销毁DOM元素,就像文档中那样: “由于状态更改,进入或离开DOM的元素触发了转换”。 如何纠正?
我的应用程序组件:
<script>
import {onMount} from 'svelte'
import Quote from './Quote.svelte'
import Button from './Button.svelte'
let quotes=""
let quote=""
onMount(async ()=> {
const res=await fetch('https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json')
quotes=await res.json()
let r=Math.ceil(Math.random()*quotes.length)
quote= quotes[r]
})
const handleClick=()=>{
quote=quotes[Math.ceil(Math.random()*quotes.length)]
}
</script>
<style>
#quote-box {
margin: 50px auto;
width: 50%;
border: 3px solid green;
padding: 10px;
text-align: center;
background: whitesmoke;
}
</style>
<div id="quote-box">
<Quote {quote} />
<Button on:newQ={handleClick}
id="new-quote">New Quote</Button>
<Button
href="{`https://twitter.com/intent/tweet?text="${quote.quote}"-${quote.author}`}"
{quote} id="tweet-quote">
Twit</Button>
</div>
我的Button组件(与带有“ a”标签的“ twit”按钮和newQuote按钮相同):
<script>
import { createEventDispatcher } from 'svelte';
export let href
export let quote
export let id
export let color
const dispatch=createEventDispatcher()
function twit() {
dispatch('twit',"");
}
function newQuote() {
dispatch('newQ',"");
}
</script>
<style>
button, a {
/* background-color:#008CBA; */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 10px;
}
#tweet-quote{
background-color:#008CBA;
}
#new-quote {
background-color: #f44336;
}
</style>
{#if href}
<a {id} target="_blank" {href} ><slot/></a>
{:else }
<button {id} on:click={newQuote}><slot/></button>
{/if}
我的报价组件:
<script>
import { scale } from 'svelte/transition';
export let quote
</script>
{#if quote}
<div class="container" transition:scale>
<p id="text">{quote.quote}</p>
<p id="author">{quote.author}</p>
</div >
{:else}
<p>loading</p>
{/if}