【问题标题】:How do I create a custom event in Svelte?如何在 Svelte 中创建自定义事件?
【发布时间】:2021-03-31 21:38:44
【问题描述】:

我一直在使用 on:click 并使用 Svelte 寻找活动。如何在子组件中触发可以在父组件中捕获的自定义事件?我看过一个教程,我可以在其中传递类似的内容,但是,我无法将其连接起来。

<Component on:customClick={myThing}>

子组件有一些看起来像这样的逻辑:

    <script>    
       export let myThing = '';
    <script>  

<input type="text" onClick={() => myThing= 'Update'} />

这似乎不起作用,我错过了什么?

【问题讨论】:

    标签: svelte


    【解决方案1】:

    或者像这样(不分派):

    家长:

    <script>
      import Child from "./Child.svelte";
    
      let count = 0;
      const handleClick = () => {
        count += 1;
      };
    </script>
    
    <main>
        <p>Parent count: {count}</p>
        <Child {count} on:click={handleClick} />
    </main>
    

    孩子:

    // child component
    <script>
        export let count;
    </script>
    
    <button on:click>
      Clicked {count}
    </button>
    

    【讨论】:

      【解决方案2】:

      您可以从子组件中调度事件并在父组件中处理它

      // children component
      <script>
          import { createEventDispatcher } from "svelte";
      
          const dispatch = createEventDispatcher();
      
          let count = 0;
      
          function handleClick() {
            count += 1;
            dispatch("customClick", {
              count
            });
          }
      </script>
      
      <button on:click={handleClick}>
        Clicked {count} {count === 1 ? 'time' : 'times'}
      </button>
      
      // parent component
      <script>
        import ChildrenComponent from "./ChildrenComponent.svelte";
      
        let count;
      
        const handleCustomClick = event => {
          count = event.detail.count;
        };
      </script>
      
      <main>
          <p>Parent count: {count || 0}</p>
          <ChildrenComponent on:customClick={handleCustomClick}/>
      </main>
      

      下面是codeandbox演示

      参考:

      Tutorials: Component events

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多