react-native可自定义联级选择器
import React, { PureComponent } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
class CustomCascader extends PureComponent {
constructor(props) {
super(props);
this.state = {
selectedOptions: [], // 用于存储选中的选项
};
}
// 模拟选项数据
options = [
{
label: '手机',
value: 'phone',
children: [
{ label: 'iPhone', value: 'iPhone' },
{ label: '华为', value: 'Huawei', children: [{ label: 'P30', value: 'P30' }] },
],
},
{
label: '笔记本电脑',
value: 'laptop',
children: [
{ label: 'MacBook', value: 'MacBook' },
{ label: 'ThinkPad', value: 'ThinkPad' },
],
},
];
// 选项点击事件处理
onOptionSelect = (option) => {
const { selectedOptions } = this.state;
// 如果有子选项,则将其推入selectedOptions,否则将其作为最终选项
if (option.children) {
this.setState({ selectedOptions: [...selectedOptions, option] });
} else {
this.setState({ selectedOptions: [...selectedOptions, option] });
// 这里可以调用props中的onChange或者其他你需要的方法
this.props.onChange(this.state.selectedOptions);
}
};
// 渲染选项组件
renderOption = (option, level = 0) => {
return (
<TouchableOpacity key={option.value} onPress={() => this.onOptionSelect(option)}>
<Text style={{ paddingLeft: level * 15 }}>{option.label}</Text>
</TouchableOpacity>
);
};
// 渲染选项列表
renderOptionsList = (options, level) => {
return options.map(option => this.renderOption(option, level));
};
// 渲染组件UI
render() {
const { selectedOptions } = this.state;
const lastOption = selectedOptions[selectedOptions.length - 1];
return (
<View>
{/* 渲染已经选择的选项 */}
{selectedOptions.map((option, index) => (
<Text key={option.value}>
{option.label}
{index < selectedOptions.length - 1 && ' > '}
</Text>
))}
{/* 如果有子选项,则渲染下一级选项 */}
{lastOption && lastOption.children && (
<View>
{this.renderOptionsList(lastOption.children, selectedOptions.length)}
</View>
)}
</View>
);
}
}
export default CustomCascader;
这个例子中,我们创建了一个名为CustomCascader
的React组件,它模拟了联级选择器的功能。组件有一个options
属性,用于模拟层级结构的选项数据。onOptionSelect
方法处理选项的点击事件,更新选中的选项到state中。\`r
评论已关闭