简体   繁体   English

Dojo 2如何实现输入的双向绑定?

[英]Dojo 2 How to achieve two-way binding for input?

How to achieve 2 way data binding for input in dojo 2? 如何在Dojo 2中实现输入的2种方式的数据绑定?

handleChange = (e) => {
  this.setState({ textValue: e.target.value });}
<Input name='title' defaultValue={this.state.textValue} placeholder='title...' onChange={this.handleChange} />

I know this is how we do in React but don't know how to achieve in dojo 2. 我知道这是我们在React中的工作方式,但不知道如何在dojo 2中实现。

In fact React supports only one-way binding, and your example illustrates it well. 实际上,React仅支持单向绑定,您的示例很好地说明了这一点。 You need to update state, to re-render react component. 您需要更新状态,以重新渲染react组件。 And as far as I understood from dojo2 docs and tutorials, there is almost same approach under the hood. 据我从dojo2的文档和教程了解,几乎有相同的方法。 Take a look here 在这里看看

Dojo 2 is built around unidirectional, top-down property propagation where it is the parent widget's job to pass properties down to its children. Dojo 2围绕单向,自上而下的属性传播而构建,这是父小部件将属性向下传递给其子级的工作。 In fact, a child widget has no direct reference to a parent widget! 实际上,子窗口小部件没有直接引用父窗口小部件! When a property changes, widgets are re-rendered (using an efficient virtual DOM) to reflect the updated state. 当属性更改时,将重新渲染窗口小部件(使用有效的虚拟DOM)以反映更新后的状态。

And it may look like this: 它可能看起来像这样:

private _addWorker() {
        this._workerData = this._workerData.concat(this._newWorker);
        this._newWorker = {};
        this.invalidate();
    }

You change data and call invalidate() to re-render widget. 您更改数据并调用invalidate()以重新呈现窗口小部件。

This is the solution to achieve 2 way data binding in Dojo 2. 这是在Dojo 2中实现2路数据绑定的解决方案。

InputWidget:- InputWidget: -

interface IInputProps {
   value: string;
   onChange(event: Event): void;
}
export class InputWidget extends WidgetBase<IInputProps> {
  private _onChange (event: Event) {
    event.stopPropagation();
    this.properties.onChange && this.properties.onChange((event.target as HTMLInputElement).value);
  }

  protected render(): DNode {
    const { value } = this.properties;
    return v('input', { 
        key: "input",
        type: "text",
        value
        onchange: this._onChange
    });
  }
}

InputWrapper widget:- InputWrapper小部件:-

export class InputWrapper extends WidgetBase<IWrapperProps> {
  private inputValue: string = ''; 
  protected inputValueChanges(value: string) {
    this.inputValue = value;
    this.invalidate();
  }

  protected render(): DNode {
    <div>
        {w(InputWidget, {onchange: this.inputValueChanges, value: this.inputValue })}
        <span>Input Value:- {this.inputValue}</span>
    </div>

  }
}

This is the solution to achieve 2 way data binding in Dojo 2. 这是在Dojo 2中实现2路数据绑定的解决方案。

Hope this will be helpful! 希望这会有所帮助! :( :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM