【问题标题】:Empty option is added to a selection dropdown in TypeScript when selecting default answer选择默认答案时,TypeScript 中的选择下拉列表中添加了空选项
【发布时间】:2021-08-06 08:32:43
【问题描述】:

所以,我有一个带有 1 个默认答案的下拉列表的选项。这是列表的代码:

renderPersonnel = (selectedRelationId: number) => HTML
${this.emptyPersonnelOption(!selectedRelationId)}
${this.personnel.map(
  ({id, name}) => 
     this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
  ))}

this.personnel 由以下代码设置:

this.personnel = await fetch(getPersonnelByFunctionUrl(functionId))
            .then(response => response.json());
          // If the list does not contain the current relation, add the current relation if it exists
          if(this.shift.relation != null && !this.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
            this.personnel.push(this.shift.relation);
          }

最后一行会检查当前选择的选项是否为已删除的关系(它仍然存在于数据库中,但在提取人员时不会包含在内。因此这一行)。

这首先渲染默认选项,代码如下:

emptyPersonnelOption = (selected: boolean) => html    
<option value="" ?selected="${selected}">- Select person -</option>

加载此选择所在的页面时,一切都很好。所有相关选项都已加载,我可以选择这些选项并保存。但是,当我想取消选择一个选项并选择默认选项时,它会出错。它会在短时间内(大约 1 秒)显示此选项,然后变为白色。

在浏览器中查看源码,原来多加了一个空选项。

之前:

之后:

在上面的图片中,我从选择的第二个选项 (Tim Batist) 开始。我将此更改为默认选项(-选择人员-)。可以看到这增加了第三个选项,几乎是空的(除了值)。

问题:
当我在此选择中更改为默认选项时,我想查看默认选项。现在它将只显示一个空白字段。我已经尝试了一些方法,但我不知道问题可能是什么。

【问题讨论】:

  • 问题可能出在您的personnelSuggestionOption 方法或任何设置this.personnel 状态的代码中。请包含该代码。
  • 尝试使用值和标签属性。可能有一个空值作为默认值,但添加一个标签,您将使用它来呈现“默认值标签”
  • @edemaine 抱歉,我正在度假,但我已使用设置this.personnel 的代码编辑了问题。希望这足够有用。
  • @Matt 这不是我们想要的。我们真的希望“标签”(作为默认值)作为一个选项。

标签: typescript select-options


【解决方案1】:

看起来您正在设置一个类变量 this.personnel,而不是使用 React 状态机制,这是正确触发更新所必需的。见React State and Lifecycle。试试这样的代码:

${this.state.personnel.map(
  ({id, name}) => 
     this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
  ))}

//...

this.setState({personnel: await fetch(getPersonnelByFunctionUrl(functionId))
            .then(response => response.json())});

          // If the list does not contain the current relation, add the current relation if it exists
          if(this.shift.relation != null && !this.state.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
            this.state.personnel = [...this.state.personnel, this.shift.relation];
          }

您还需要在构造函数中初始化this.state.personnel,如下所示:

constructor() {
  this.state = {personnel: []};
}

【讨论】:

  • 这不太行,但我认为这是我的错。这是一个 TypeScript 文件,但我不确定这是否重要。我会更新问题。对不起这个错误。
猜你喜欢
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多