react-dates的renderMonthElement内react-select选中后值不更新问题
问题根源
react-dates 内部对 renderMonthElement 做了渲染优化,只有当它感知到内部状态变化时才会重新渲染该区域,你外部维护的 bdaymonth 状态更新不会触发该区域的重渲染,所以 Select 组件的显示值不会同步更新。同时你对 react-select 的 value 属性绑定也不符合组件要求:react-select 的 value 要和 options 里的项结构完全一致,你传入的是字符串类型的 bdaymonth,但 options 里的项是 {value: 数字, label: 字符串} 结构,这也会导致显示异常。
解决方案
直接使用 renderMonthElement 入参里的 month 对象作为值的来源,不需要额外维护 bdaymonth 状态同步,同时修正 value 的绑定格式即可:
- 直接通过
month.month()拿到当前选中的月份索引(0-11),匹配到对应的 options 项传给 Select 的 value 属性 - 选值时只需要调用 react-dates 提供的
onMonthSelect方法,内部会自动更新 month 状态并触发区域重渲染
修正后的完整代码
const renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => { // 生成年份选项 const years = [] for (let i = moment().year() - 16; i >= moment().year() - 100; i--) { years.push( <option value={i} key={`year-${i}`}> {i} </option> ) } // 生成月份选项 const months = moment.months().map((label, value) => { return { value: value, label: label } }) // 匹配当前选中的月份项 const selectedMonth = months.find(item => item.value === month.month()) return ( <BdaySelect> <div> <Select placeholder="Monat" styles={{ indicatorSeparator: () => {}, ...customStyles }} options={months} filterOption={createFilter(filterConfig)} name="months" value={selectedMonth} className="landSelect" onChange={optionSelected => { onMonthSelect(month, optionSelected.value) }} /> </div> <div> <select value={month.year()} onChange={e => onYearSelect(month, e.target.value)} > {years} </select> </div> </BdaySelect> ) }
如果仍然存在重渲染问题,可以给使用的 SingleDatePicker 组件添加 key 属性,值为当前选中的月份和年份的组合,强制组件重渲染:
<SingleDatePicker key={`${selectedDate.month()}-${selectedDate.year()}`} // 其余原有属性保持不变 renderMonthElement={renderMonthElement} />
内容的提问来源于stack exchange,提问作者Martin Conde
相关产品推荐
相关产品推荐

