英文:
Add class to svelte component
问题
Sure, here is the translated code part without additional content:
- btn.svelte
<button class="btn"></button>
- btnHold.svelte
<script>
import Btn from './btn.svelte';
</script>
I'm trying to add a new class btn--hold to btn.svelte
<Btn class="{btn} btn--hold"></Btn>
I get an error on class.
Basically I would like in the end to have:
<button class="btn btn--hold"></button>
How can I add a class to an imported component?
英文:
I created two components:
1. btn.svelte
<button class="btn" />
2. btnHold.svelte
<script>
import Btn from './btn.svelte';
</script>
I'm trying to add a new class btn--hold to btn.svelte
<Btn class="{btn} btn--hold" />
I get an error on class.
Basically I would like in the end to have:
<button class="btn btn--hold" />
How can I add a class to an imported component?
答案1
得分: 5
class 是受保护的关键字,您可以通过像这样更改名称来解决这个问题:
<script>
// ...
let className = '';
export { className as class };
</script>
<button class="btn {className}" ...
用法示例(btn 类已在内部添加):
<Btn class="btn--hold" ...
英文:
class is protected keyword, you can work around that by changing the name like this:
<script>
// ...
let className = '';
export { className as class };
</script>
<button class="btn {className}" ...
Usage example (btn class is already added internally):
<Btn class="btn--hold" ...
答案2
得分: 1
你可以通过从组件中导出一个名为 className 的变量,并将其添加到按钮的现有类中来实现:
- btn.svelte
<script>
export let className;
</script>
<button class="btn {className}" />
- btnHold.svelte
<script>
import Btn from './btn.svelte';
</script>
<Btn class="btn--hold" />
以将 btn--hold 类添加到按钮上。
英文:
You could do it by exporting a className variable from the component, and adding it onto the button's existing class
- btn.svelte
<script>
export let className;
</script>
<button class="btn {className}" />
- btnHold.svelte
<script>
import Btn from './btn.svelte';
</script>
<Btn class="btn--hold" />
to add the btn--hold class to the button.
答案3
得分: 1
在btn.svelte组件中,你可以这样做:
<button class={'Btn ' + ($$restProps.class ?? '') } />
$$restProps变量是一个包含传递给组件的属性的对象,但这些属性没有通过export let关键字明确声明为props。- 我使用了nullish coalescing运算符
??,因为如果你没有传递class属性给组件,结果将会是Btn undefined。
现在,在btnHold.svelte组件中,你只需这样做:
<Btn class="btn--hold" />
可工作的REPL示例在这里:https://svelte.dev/repl/c2b6625ed73144eeb6bebce6ea4a4d82?version=3.58.0
英文:
In the btn.svelte component you can do:
<button class={ 'Btn ' + ($$restProps.class ?? '') } />
- The
$$restPropsvariable is an object of attributes which were passed to the component, but not explitly declared as props via theexport letkeyword. - I used the nullish coalescing operator
??, because if you don't pass theclassattribute to the component, the result will beBtn undefined.
Now, in the btnHold.svelte component you simply do:
<Btn class="btn--hold" />
Working REPL here: https://svelte.dev/repl/c2b6625ed73144eeb6bebce6ea4a4d82?version=3.58.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论