首页 > 解决方案 > 没有调用 Office-fabric-react 文本字段的 onChange

问题描述

onChange因为我的组件没有触发:

<TextField 
label = "City"
required = {true}
placeholder = "Location"
value = {this.props.location && this.props.location.Title ?  this.props.location.Title : ""}
onChange = {this._onChangeTitle.bind(this)}
onChanged = {(newValue: string) => {
    console.log("onChanged | newValue: ", newValue);
}}

private _onChangeTitle(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue: string): void {
    console.log("AddRemoveComponent | _onChangeTitle | newValue: ", newValue);

    this._location.Title = newValue;

    console.log("AddRemoveComponent | _onChangeTitle | this._location.Title: ", this._location.Title);
}

onChanged记录新值,但_onChangeTitle永远不会被调用。

有什么建议么?

标签: javascripttypescript

解决方案


在最新版本的事件应该按预期触发,这里有一个演示供您参考。office-ui-fabric-react TextField.change

避免使用箭头函数并在render方法中绑定(有关更多详细信息,请参见此处),因为它可能会影响性能,而一种选择是手动绑定构造函数中的方法:

 export class TextFieldBasicExample extends React.Component<any, any> {
  private location: {Title:string};

  constructor(props: {}) {
    super(props);
    this.location = {Title:""};
    this.onChange = this.onChange.bind(this);
    this.onChanged = this.onChanged.bind(this);
  }

  public render(): JSX.Element {
    return (
      <div>
        <TextField
          onChange = {this.onChange}
          onChanged={this.onChanged} />
      </div>
    );
  }

  private onChange(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue: string): void {
    this.location.Title = newValue;
  }

  private onChanged(newValue: string): void {
        this.location.Title = newValue;
  }
}

推荐阅读