Clearing inputText using react-bootstrap-typeahead when invalid data is entered

非 Y 不嫁゛ 提交于 2021-01-27 20:02:19

问题


I'm trying to validate a selection using react-bootstrap-typeahead and clear out the input text if invalid when I move to another area of the page.

I can't figure out a good way to do this.

The onBlur for the Typeahead component doesn't fire at the right time to validate and clear.

Any suggestions would be appreciated

Here is my typeahead definition

        <Typeahead  bsSize="sm"
                    defaultSelected = {this.props.options.slice(selectedIndex)}
                    clearButton
                    labelKey="roomNumber"
                    options={this.props.options}
                    placeholder={this.props.placeholder}                          
                    name={this.props.nameId}
                    ref={ref => this.roomChoice = ref}
                    onChange={this.onChangeHandler.bind(this)}
                    onInputChange={this.onInputChangeHandler.bind(this)}
                    onBlur={this.onBlurHandler.bind(this)} 
                    onFocus={this.onFocusHandler.bind(this)} 
                  />

Here is my onBlur Function:

onBlurHandler(event)
{   
         if (this.roomInputText)
        {
            if (!this.roomSelectedOption)
            {
                this.roomChoice.getInstance().clear()
            }
        }

}

The onBlur isn't firing in the right time for me to have a selected option if someone entered text.


回答1:


Get the ref in TypeAhead instance and use in onchange event call.

<div>
  <Typeahead
    options={[...]}
    ref={(ref) => this._typeahead = ref}
    onInputChange={this.onInputChangeSelection}
 />
</div>




onInputChangePartsSelection = (value) => {
    if (value) {
    const instance = this._typeahead.getInstance()
    instance.clear()
    instance.focus()
    }
  }



回答2:


I was using AsyncTypeAhead and had to do the following.

var asyncTypeAhead = typeAhead as AsyncTypeahead;
asyncTypeAhead.getInstance().clear();

I found this post useful https://github.com/ericgio/react-bootstrap-typeahead/issues/359



来源:https://stackoverflow.com/questions/45987582/clearing-inputtext-using-react-bootstrap-typeahead-when-invalid-data-is-entered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!