探秘React Native Tree Select:构建高效多级选择器的利器
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import TreeSelect from 'react-native-tree-select';
const data = [
{
label: 'Node 1',
value: 'node1',
children: [
{ label: 'Child 1', value: 'child1' },
{ label: 'Child 2', value: 'child2' }
]
},
{
label: 'Node 2',
value: 'node2'
}
];
const TreeSelectExample = () => {
const [selectedValue, setSelectedValue] = React.useState(null);
return (
<View style={styles.container}>
<TreeSelect
data={data}
value={selectedValue}
onChange={setSelectedValue}
style={styles.treeSelect}
/>
<View style={styles.selectedContainer}>
<Text>Selected Value: {selectedValue}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20
},
treeSelect: {
width: '100%',
height: 300
},
selectedContainer: {
marginTop: 20,
padding: 10,
backgroundColor: '#ddd'
}
});
export default TreeSelectExample;
这个代码示例展示了如何在React Native应用中使用react-native-tree-select
库来创建一个多级选择器。代码中定义了一个简单的树状数据结构,并使用TreeSelect
组件来渲染它。用户可以选择任何节点,选择的值会实时更新并显示在屏幕上方的文本组件中。
评论已关闭