【问题标题】:Reactive deceleration in svelte not working as expected苗条的反应性减速没有按预期工作
【发布时间】:2019-11-25 11:51:24
【问题描述】:

我正在尝试创建一个 TextAreaAutosize 组件,该组件返回一个 textarea,它会在需要时自动调整其高度。

我想在高度变化时运行 onHeightChange 函数,所以我使用了细长的响应式语句($:),这样每当高度变化时,这段代码就会运行。

App.svelte

<script>
  import TextArea from "./TextAreaAutosize.svelte";
  let val, ref;
</script>

<TextArea 
  bind:value={val}  
  bind:ref={ref} 
  style={"height: 90px; maxHeight=40"} 
  minRows={4}
 />

TextAreaAutosize.svelte

<script context="module">
  import calculateNodeHeight from './calculateNodeHeight.js'
  let uid = 0;
  const noop = () => {};
</script>

<script>
  export let value = '';
  export let style;
  export let useCacheForDOMMeasurements = false;
  export let minRows = -Infinity;
  export let maxRows = +Infinity;
  export let onHeightChange = noop;
  export let ref = null;

  let refConfig = {
    _uid: uid++
  }

  let state = {
    height: 0,
    minHeight: -Infinity,
    maxHeight: +Infinity
  }

  // runs when change in height
  $: if(state.height){

    //block 1

    console.log('height changed')
    onHeightChange(refConfig)

  }

  // resizes element on initial mount or whenever change in value
  $:if(ref || value){

     //block 2

    _resizeComponent()

  }

  // function for resizing textarea when required
  function _resizeComponent(){
    if(!ref){
      return;
    }

    const refHeight = calculateNodeHeight(
      ref,
      refConfig._uid,
      useCacheForDOMMeasurements,
      minRows,
      maxRows
    );

    const {
      height,
      minHeight,
      maxHeight,
      rowCount,
      valueRowCount
    } = refHeight;

    refConfig.rowCount = rowCount;
    refConfig.valueRowCount = rowCount;

    if(
      state.height !== height ||
      state.maxHeight !== maxHeight ||
      state.minHeight !== minHeight
    ){
      state = {height, minHeight, maxHeight}
    }
  }

</script>

<textarea 
  bind:value={value} 
  bind:this={ref} 
  style={`${style};height: ${state.height}px;`}
  on:click
  on:change  
  class={$$props.class}
/>

在这个组件中,只要 state.height 发生变化,块 1 就应该运行。但它根本不运行。但是当我把它放在 block2 之后,只要 state.height 发生变化,它就会运行

当 textarea 的值改变 block2 运行并调用 _resizeComponent 时,如果需要,它会使用新的高度更新状态。如果高度变化,它应该触发 block1。但只有当我将它放在 block2 之后才会触发该块

我无法理解为什么我的代码中有这种行为。无论响应式语句的顺序如何,只要 state.height 发生变化,block1 中的语句就应该运行

【问题讨论】:

    标签: svelte


    【解决方案1】:

    通过分析该代码,Svelte 无法确定第二个块可能会影响 state 的值。所以它不会重新排序块以首先运行第二个。 (如果最后有意外的变化,它不能只是继续重新运行反应块;那样就是无限循环。)

    如果不仅仅是_resizeComponent() 而是state = _resizeComponent(),并且相应地更改了功能,那将会改变。或者,只需手动重新排序块。

    顺便说一句,有一种更简单的方法来获得自动调整大小的文本区域:https://svelte.dev/repl/40f4c7846e6f4052927ff5f9c5271b66?version=3.6.8

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2019-05-18
      • 2021-05-26
      • 2021-06-12
      • 2018-08-20
      • 2011-08-30
      • 2015-03-23
      • 2019-01-08
      • 2017-07-18
      相关资源
      最近更新 更多