【问题标题】:Dropdown shows empty when selected Reactjs选择 Reactjs 时下拉菜单显示为空
【发布时间】:2018-03-22 17:17:47
【问题描述】:

ReactJs

当我使用e.target.value 时,我的下拉菜单会更新,但当我使用e.target.options[e.target.selectedIndex].text 时,我的下拉菜单不会更新,但文本实际上设置为声明的状态。可能是什么问题呢?我需要帮助。

在我的 onChange 中,我有:

handleChange(e) {
        const { name, value, selectedIndex, options} = e.target

        if (name == "fundingInstitutionName") {
            this.setState({
                fundingInstitutionName: options[selectedIndex].text,
                bank_code: value
            }, () => {
                this.validateAccountNum();
            })
        } else {
            this.setState({
                [name]: value
            }, () => {
                this.validateAccountNum();
            })
        }

    }

虽然我在选择下拉菜单中有这个,

<select 
     className="form-control kyc-input"
     value={this.props.state["fundingInstitutionName"]}
     onChange={(e) => this.props.handleChange(e)}
     name="fundingInstitutionName" required>

     <option value="">Select bank</option>
        {bNames.map((bName, i) => {
            return <option key={i} value={bName.code}>
                        {bName.name}
                    </option>
         })}

</select>

注意:我需要值和文本,因为它们是分开的。

【问题讨论】:

  • 提供代码以便我了解实际发生的情况。
  • 为您从 e.target 设置的值添加 console.log 并查看您得到的结果。
  • 我得到了对应于 bName.code 的值和对应于 bName.name 的文本,它们都是预期的,但下拉列表没有物理更新,我的意思是它是空的(它没有根本不显示)@Rahamin

标签: reactjs select web option setstate


【解决方案1】:

您正在从this.props.state["fundingInstitutionName"] 设置选择的值。

我假设您打算将其设置为 this.state["fundingInstitutionName"].

还有一件事:在handleChange 中,您应该设置您从中设置选择值的状态变量,但有时您会这样做:

this.setState({
  [name]: value
}

这不会反映在选择的值中...

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2020-05-14
    • 2020-04-12
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多