我有一个项目列表,每个具有主体和源泉。目前,它呈现这样的:
const ListItem = (props) => {
const {body, source} = props.context;
return (
<View style={styles.item}>>
<View style={{backgroundColor: 'lightblue'}}>
<Text style={styles.body}>{body}</Text>
</View>
<View style={{backgroundColor: 'lightyellow'}}>
<Text style={styles.source}>{source}</Text>
</View>
</View>
);
}
这是一个很多嵌套和容器。难道是更优化呢?
我要张贴作为回答我的意见。
以前的评论:
我想这取决于你的设计,据我所知,这是好的内无反应原住民假设你使用的渲染列表的优化方式(例如,使用FlatList或类似)
根据你的下面的评论,我不认为这是可怕的。
这里有一个替代方案。然而,为便于阅读我更希望你在你的问题张贴片段。
const ListItem = props => {
const items = [
{ key: 'body', backgroundColor: 'lightblue' },
{ key: 'source', backgroundColor: 'lightyellow' }
];
return (
<View style={styles.item}>
{
items.map(({ key, backgroundColor }) =>
<View style={{ backgroundColor }}>
<Text style={styles[key]}>
{ props[key] }
</Text>
</View>
)
}
</View>
)
}
文本组件确实需要的backgroundColor这样你就可以让两个观走:
<View style={styles.item}>
<Text style={[styles.body, {backgroundColor: '...'}]}>{body}</Text>
<Text style={[styles.source, {backgroundColor: '...'}]}>{source}</Text>
</View>
另外,我不知道styles.item所包含的内容,但如果你要一路走下去,你可能会取代其他容器景观并React.Fragment。