如何在React Native中创建类似于HTML无序列表(<ul>
)的列表?需要使用基于flex的布局并使用两个View
元素(一个用于包含“项目符号”,另一个用于列表项文本),还是有更简单、不那么繁琐的方法吗?
如何在React Native中创建类似于HTML无序列表(<ul>
)的列表?需要使用基于flex的布局并使用两个View
元素(一个用于包含“项目符号”,另一个用于列表项文本),还是有更简单、不那么繁琐的方法吗?
ListView
(请参见项目符号的renderRow
函数):
class TestProject extends React.Component {
constructor() {
super();
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}).cloneWithRows(['string1', 'string2', 'string3']),
};
}
renderRow(data) {
return (
<Text>{`\u2022 ${data}`}</Text>
);
}
render() {
return (
<ListView
style={{margin: 40}}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
/>
);
}
}
如果您需要防止文本绕着符号排列,您实际上需要使用多个组件,正如问题中所建议的。例如:
renderRow(data) {
return (
<View style={{flexDirection: 'row'}}>
<Text>{'\u2022'}</Text>
<Text style={{flex: 1, paddingLeft: 5}}>{data}</Text>
</View>
);
}
<ul>
所能实现的防止列表项内容在符号下方换行的功能。请查看您在此处提供的代码:https://rnplay.org/apps/M5zw5Q -- 如何修改以防止文本换行? - Steed-Aspreyexport const UnorderedList = ({texts}: {texts: string[]}) => {
return (
<Column>
{texts.map((t, index) => (
<Row key={index}>
<Column
style={{
alignSelf: 'flex-start',
justifyContent: 'flex-start',
marginRight: 12,
transform: [{scale: 2.5}],
}}>
<Text
style={{
alignSelf: 'flex-start',
justifyContent: 'flex-start',
}}>
{'\u2022'}
</Text>
</Column>
<Column>
<Text>{t}</Text>
</Column>
</Row>
))}
</Column>
);
};
const Column = ({children,style})=>{
return <View
style={[{display: 'flex', flexDirection: 'column'},style]}>
{children}
</View>
}
const Row = ({children,style})=>{
return <View
style={[{display: 'flex', flexDirection: 'row'},style]}>
{children}
</View>
}
<View>
{ListItems.map(
(item, index) => (
<Text>
{"\u2B24" + " "}
{item}
</Text>
)
)}
</View>
可以使用@jsamr/react-native-li
库来实现此目的。
npm add --save @jsamr/react-native-li @jsamr/counter-style
MarkedList
组件的子元素将被包裹在一个标记视图中:
import React from 'react';
import { ScrollView, StyleSheet, Text } from 'react-native';
import disc from '@jsamr/counter-style/presets/disc';
import MarkedList from '@jsamr/react-native-li';
export default function App() {
return (
<ScrollView style={{ flexGrow: 1 }}>
<MarkedList counterRenderer={disc}>
{[...Array(100).keys()].map((index) => (
<Text key={index} style={{ flexShrink: 1 }}>
The World Wide Web Consortium (W3C)
develops international standards
for the web and HTML, CSS, and more.
</Text>
))}
</MarkedList>
</ScrollView>
);
}
你也可以尝试使用一个 View,将其设置为一个带有 Text 组件的 View,并且该 View 具有 flexDirection: 'row'
<View style={{height:5, width: 5, backgroundColor: '#000', borderRadius: 20}} />