react-native没有提供select控件,这里使用第三方控件react-native-modal-dropdown,但是在做级联的时候发现存在问题。在源码基础上做了一些修改。
react-native-modal-dropdown版本为0.6.0
级联出现异常现象的原因为,defaultValue和buttonText的配合没有加入级联的逻辑,导致无法级联显示不正常
新增buttonRefresh状态,用来表示是否触发button的显示值的改变
this.setState({
buttonText: value,
buttonRefresh: false, // add by wulinfeng 2018-01-20
selectedIndex: idx
});
修改_renderButton如下:
_renderButton() {
// 加入级联功能 by wulinfeng 2018-01-20
let value = this.state.buttonText;
if(this.state.buttonRefresh)
value = this.props.defaultValue;
return (
this._button = button}
disabled={this.props.disabled}
accessible={this.props.accessible}
onPress={this._onButtonPress.bind(this)}>
{
this.props.children ||
(
{value}
)
}
);
}
select(idx) {
let value = this.props.defaultValue;
if (idx == null || this.props.options == null || idx >= this.props.options.length) {
idx = this.props.defaultIndex;
}
if (idx >= 0) {
value = this.props.options[idx].toString();
}
this._nextValue = value;
this._nextIndex = idx;
this.setState({
buttonText: value,
buttonRefresh: false, // add by wulinfeng 2018-01-20
selectedIndex: idx
});
}
修改_onRowPress如下
_onRowPress(rowData, sectionID, rowID, highlightRow) {
const { onSelect, renderButtonText, onDropdownWillHide } = this.props;
if (!onSelect || onSelect(rowID, rowData) !== false) {
highlightRow(sectionID, rowID);
this._nextValue = rowData;
this._nextIndex = rowID;
this.setState({
buttonRefresh: false, // add by wulinfeng 2018-01-20
buttonText: renderButtonText && renderButtonText(rowData) || rowData.toString(),
selectedIndex: rowID
});
}
if (!onDropdownWillHide || onDropdownWillHide() !== false) {
this.setState({
buttonRefresh: false, // add by wulinfeng 2018-01-20
showDropdown: false
});
}
}
第一次渲染的时候需要将buttonRefresh状态改为true,比如
componentDidMount(){
this.refs.select.setState({
buttonRefresh: true
});
}
调用的时候,在级联重新指定其他select的值得时候需要将buttonRefresh状态改为true,比如
componentWillUpdate(nextProps, nextState){
this.refs.select.setState({
buttonRefresh: true
});
}