nextProps.defaultIndex !== prevState.defaultIndex) {
return {
list: nextProps.list,
index: nextProps.defaultIndex
}
}
return null
}
constructor (props) {
super(props)
this.state = {
list: props.list,
index: props.defaultIndex
}
this.onValueChange = this.onValueChange.bind(this)
}
onValueChange (itemValue, itemIndex) {
this.setState( // setState不是立即渲染
{
index: itemIndex
},
() => {
this.props.onChange && this.props.onChange(itemIndex)
})
}
render() {
// Picker的接口直接看react native的文档https://reactnative.cn/docs/picker/
const { list = [], index = 0 } = this.state
const value = list[index]
const Items = list.map((obj, index) => {
return <Picker.Item key={index} label={obj.label} value={obj} />
})
return (
<Picker
selectedValue={value}
style={{ flex: 1 }}
mode="dropdown"
onValueChange={this.onValueChange}>
{Items}
</Picker>
)
}
}
renderItems()中PickerItem的回调函数onChange
onChange (itemIndex, currentIndex) { // itemIndex选中的是第几项,currentIndex第几级发生了变化
const indexArr = []
const { options = [], indexs = [] } = this.state
const re = (arr, index) => { // index为第几层,循环每一级
if (arr && arr.length > 0) {
let childIndex
if (index < currentIndex) { // 当前级小于发生变化的层级, 选中项还是之前的项
childIndex = indexs[index] 关键词:如何封装一个React Native多级联动(代码完成)