【发布时间】:2020-01-25 01:02:31
【问题描述】:
我有一个带有来自 react-select 的 <Select options={myoptions} onChange={this.mychangehandler}/> 元素的反应组件。我已经使用可以访问的 redux 保存了一些设置,例如使用this.props.myreducer.dropdownvalue(已经测试过了,第一次渲染组件的时候值是可用的)
根据 redux 道具,我想自动选择下拉列表中的选项之一。如果this.props.myreducer.dropdownvalue 等于1,我如何告诉<Select.../>dropdown 自动选择选项2?
有无数的属性,但不知何故,我找不到可以帮助我自动选择正确条目的属性。
有什么想法吗?自动触发 onChange 的解决方案也是首选,但如果不是,应该没问题。
提前致谢:)
问候克里斯蒂安
编辑:这是完整的代码:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import Auxiliary from '../../../../../../../hoc/Auxiliary/Auxiliary';
import classes from './Dropdown.module.css';
import Select from 'react-select';
class Dropdown extends Component {
changeSetting = (event) => {
console.log('qid'+this.props.qid)
console.log('event: '+JSON.stringify(event))
if(this.props.certs.certquestions[this.props.qid].red === event.id)
{
this.props.colorchanger("red")
}else if(this.props.certs.certquestions[this.props.qid].yellow === event.id)
{
this.props.colorchanger("yellow")
}else if(this.props.certs.certquestions[this.props.qid].green === event.id)
{
this.props.colorchanger("green")
}
}
render(){
const options = []
const qid = this.props.qid
console.log('qid:'+qid)
const question = this.props.certs.certquestions[qid]
const opt = question.options.split("|")
for(let i = 0;i<opt.length;i++){
let optname = opt[i]
options.push({value:i, label:optname, id:i})
}
let notes = "";
let selectedOption = null;
if(this.props.loadp)
{
let progress = this.props.certs.loadedProgress[this.props.users.users[this.props.users.currentuser].target_id+'_'+this.props.q]
if (typeof progress !== 'undefined')
{
notes = progress.notes
selectedOption = progress.selectedOption
}
}
return(
<Auxiliary>
<h3>{question.title}</h3>
<Select className = {classes.Dropdown} options={options} onChange={this.changeSetting}/ value={selectedOption}> //selectedOption is an Integer
<textarea value = {notes}/>
</Auxiliary>
)
}
}
const mapStateToProps = state => {
return {
certs: state.certs,
users: state.users
};
}
export default connect(mapStateToProps, null)(Dropdown);
选项有不同的标签和值以及从 0 到 9 的 ID。我尝试将 value={selectedOption} 添加到 Select 元素,也尝试使用标签代替,但它始终只显示“Select...”占位符并且不选择该选项并触发 onChange。知道我做错了什么吗?
已解决:我现在知道我做错了什么,非常感谢 :) 我需要将具有值、id 和标签的对象传递给值 :)
【问题讨论】:
-
尝试分享您的完整代码,或者更好地为您的代码制作一个代码框场景。
-
你使用“value”属性吗?
-
是的,我用 value、defaultValue 和 defaultInputValue 尝试过,但没有一个选择正确的条目
-
在这种情况下 value 属性是必需的。没有价值就行不通。你能展示你如何使用它的价值吗?可能是你用错了。
-
好的,抱歉,已编辑
标签: javascript reactjs react-select