我正在使用SvelteKit和Tailwind构建一个应用程序.我知道,在使用Tailwind进行样式设计时,建议利用组件来减少使用Tailwinds实用程序类编写的重复代码量.我的问题是,当基于HTML标记(例如<input>标记)制作组件时,处理该组件中通常只是该标记属性的props 变得越来越困难.MDN显示<input>标记有31个可能的属性.我知道我不会全部使用它们,但来回地将它们作为props 添加到组件中会让人感到厌烦.

如果不向组件添加多达31行(共export let attribute行)并将其添加到组件内部的real HTML标记中,解决此问题的最佳方法是什么?

示例:

<script>
    export let name;
    export let id;
    export let type;
    export let disabled;
    export let required;
    export let minLength;
    export let maxLength;
    export let min;
    export let max;
    export let pattern;

    let value;
    let borderColor = '#D1D5DB';

    const inputHandler = (e) => {
        if (e.target.value === '') {
            borderColor = '#D1D5DB';
        } else {
            borderColor = '';
        }
    };
</script>

<input
    {name}
    {id}
    {type}
    {disabled}
    {required}
    {minLength}
    {maxLength}
    {min}
    {max}
    {pattern}
    on:input={inputHandler}
    style={`border-color: ${borderColor}`}
    class="
    w-full px-1 py-px mb-4 bg-transparent border-2 border-gray-300 
    rounded-xl last:mb-0 valid:border-emerald-300 invalid:border-rose-400
  "
/>

推荐答案

Alternatively to using the $$restProps (and based on @pilchard's comment above, thanks for that) an options object could be exported, which is holding all the modified attributes values and is spread after the default attributes defined on the input element inside the component
Like this all possible attributes of the element can be used/set without having to write them all out anywhere REPL

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

    const options ={
        type: 'number',
        placeholder:'input a number',
        required: true
    };
</script>

<Input {options} />
Input.svelte
<script>
    export let options = {}
    export let value = ''
</script>

<input type="text"
       placeholder="default placeholder"
       {...options}
       bind:value
       style:border-color="{options.required && value === '' ? 'tomato' : ''}"
       class="w-full px-1 py-px mb-4 bg-transparent border-2 ..."
       />

Javascript相关问答推荐

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

如何在RTK上设置轮询,每24小时

基于变量切换隐藏文本

React 17与React 18中的不同setState行为

为什么这个JS模块在TypeScript中使用默认属性导入?""

Promise Chain中的第二个useState不更新

CheckBox作为Vue3中的一个组件

如何将Openjphjs与next.js一起使用?

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

Vaadin定制组件-保持对javascrip变量的访问

JS Animate()方法未按预期工作

Phaser3 preFX addGlow不支持zoom

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

如果我的列有条件,我如何呈现图标?

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

如何检测当前是否没有按下键盘上的键?

是否有静态版本的`instanceof`?

Firefox的绝对定位没有达到预期效果

从客户端更新MongoDB数据库

带有JS模块模式的Rails的Importmap错误:";Net::ERR_ABORTED 404(未找到)&Quot;