如何在<tagsinput>上显示验证消息以使预制组件对唯一值产生反应

时间:2018-08-15 13:52:48

标签: reactjs

我有一个来自react-tagsinput的输入标签组件,如下所示:

const onTagChange = (tags) => {
  const noDuplicateTags = tags.filter((v, i) => tags.indexOf(v) === i);
  const duplicateEntered = tags.length !== noDuplicateTags.length;

  if (duplicateEntered) {
    onTagChange(tags);
    console.log('duplicate');
  }

  onTagChange(noDuplicateTags);
};

function TagContainer({
  tags,
}) {
  return (
    <div>
      <Header>Meta:</Header>
      <TagsInput value={tags} onChange={onTagChange} />
    </div>
  );
}

TagContainer.propTypes = {
  tags: PropTypes.arrayOf(PropTypes.string),
};

TagContainer.defaultProps = {
  tags: [],
};

导出默认TagContainer; 以及onTagChange方法的实现,该方法作为道具传递给另一个组件中的<TagContainer>组件。

 export class Modal extends React.Component {
...
...
 onTagChange = (tags) => {
 this.props.onTagChange(tags);
}

...
...
render() {
 return(
   <TagContainer
        tags={tags}
        onTagChange={this.onTagChange}
      />
 );
}
}

问题:onlyUnique组件中的<TagsInput>属性设置为true,以避免重复输入。但是,一旦用户输入重复值,我就需要显示一条错误消息,指出“重复值”。尤其是在第三方组件上,如何才能做到这一点。

1 个答案:

答案 0 :(得分:0)

我认为您将不得不处理组件中的重复项,因为您没有收到<TagInput />组件的反馈。

在更高层次上,我会做这样的事情

class Example extends React.Component {
  constructor() {
    super();

    this.state = {
      showDuplicateError: false
    };
  }

  handleTagChange(tags) {
    const uniqueTags = removeDuplicates(tags);
    const duplicateEntered = tags.length !== uniqueTags.length;

    if (duplicateEntered) {
      this.showDuplicateError();
    }

    // add unique tags regardless, as multiple tags could've been entered
    const { onTagChange } = this.props;
    onTagChange(uniqueTags);
  }

  showDuplicateError() {
    this.setState({
      showDuplicateError: true
    });
  }

  render() {
    const { showDuplicateError } = this.state;
    const { tags } = this.props;
    return (
      <React.Fragment>
        { showDuplicateError && <div>Duplicate entered</div>}
        <TagsInput value={ tags } onTagChange={ this.handleTagChange } />
      </React.Fragment>
    );
  }
}