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>
)
}
}
// Modal 安卓上无法返回
class Pickers extends Component {
static propTypes = {
options: PropTypes.array,
defaultIndexs: PropTypes.array,
onClose: PropTypes.func,
onChange: PropTypes.func,
onOk: PropTypes.func,
}
static getDerivedStateFromProps(nextProps, prevState) { // options数据选项或指定项变化时重新渲染
if (nextProps.options !== prevState.options
关键词:如何封装一个React Native多级联动(代码完成)