Office ui面料清除文本字段

时间:2018-10-25 08:42:58

标签: reactjs typescript textfield office-ui-fabric

我的问题是我想用一个按钮清除Office UI Fabric中的带遮罩的文本字段。有没有人计划如何做到这一点?

我试图用状态设置值,但这不起作用。

1 个答案:

答案 0 :(得分:0)

似乎MaskedTextField也不直接支持它,至少value的非setValue属性不会导致组件重新呈现。

但是,重新安装组件的技术(例如,参见here)在这里很受欢迎。 要重置值,将实例化并安装MaskedTextField组件的新实例,为此引入了以下组件:

class MaskedTextFieldWrapper extends React.Component<any, any> {
  private textFieldRef: React.RefObject<MaskedTextField>;

  public generateKey(prefix:string): string {
    return `${ prefix }_${ new Date().getTime() }`;
  }

  public render(): JSX.Element {
    if(this.props.resetValue){
      return <MaskedTextField key={ this.generateKey("textfield")} value='' ref={this.textFieldRef} {...this.props} />;  
    }
    return <MaskedTextField ref={this.textFieldRef} {...this.props} />;
  }
}

现在可以像这样重置MaskedTextField的值:

class TextFieldExample extends React.Component<any, any> {

  constructor(props:any) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      resetValue: false
    };
}


  public handleClick():any {
    this.setState({resetValue: true});
  }

  public render(): JSX.Element {
    return (
      <div>
        <MaskedTextFieldWrapper resetValue={this.state.resetValue}  label="With number mask" mask='9999' />
        <PrimaryButton onClick={this.handleClick}>Clear</PrimaryButton>
      </div>
    );
  }

}

Demo