javascript 如何清除React标签输入字段?

utugiqy6  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(152)

react-tag-autocomplete库中,需要添加手动建议。因此,我为建议列表创建了一个名为ReactTagsSuggestions的新组件。
如何清除ReactTags的输入字段

<ReactTags
  id="form-share"
  tags={selectedTags}
  // suggestions={tagSuggestions}
  handleAddition={this.props.handleAddition}
  handleDelete={this.props.handleDelete}
  placeholder={this.props.tags.length ? '' : tr('Share with users, groups, and channels')}
  tagComponent={this.selectedTags}
  handleInputChange={this.handleInputChange}
  autofocus={false}
/>
<ReactTagsSuggestions
  suggestionList={tagSuggestions}
  showSuggestions={tagSuggestions.length > 0}
  checkToShare={this.props.checkToShare}
/>
iih3973s

iih3973s1#

如果你创建一个像这样的函数

handleDelete = () => {
  this.setState({ tags: [] })
}

并将其传递给ReactTags组件

<ReactTags
.
.
handleDelete={ this.handleDelete }
/>

cx6n0qe3

cx6n0qe32#

要清除ReactTags的输入字段,可以将selectedTags重置为空数组:

clearTag() {
  this.setState({ selectedTags: [] });
}

// Call the clearTag somwhere in your app
<button type="button" onClick={this.clearTag}>Clear tags</button>

示例:https://codesandbox.io/s/react-tags-v9mft

wh6knrhe

wh6knrhe3#

太晚了,但可能对其他人有用。我想你是指清除输入值而不是标记。下面是useStateReactTagsinputValue属性的解决方案

const [inputValue, setInputValue] = useState('');
<ReactTags
    inputValue={inputValue}
    handleAddition={(...args) => {
        myHandleAddition(args);
        setInputValue('');
    }}
    handleInputChange={(tag) => {
        if (tag.slice(-1) === ' ') {
            myHandleAddition([{ id: tag, text: tag }]);
            setInputValue('');
        } else {
            setInputValue(tag);
        }
    }}
/>

相关问题