我试图ListItem
通过按下它来改变视图。在我的屏幕中,这是普通的 React 组件,我有功能List
组件和 selectedItemState(只会选择 1 个或不选择任何项目)。其中List
也很少有功能ListItem
组件。问题是缺乏重新渲染项目的能力。
正如官方 React 页面所说,我已经尝试过备忘录,但没有结果。将组件更改为普通组件会产生相同的结果。
屏幕组件:
export default class myScreen extends Component {
constructor () {
super ()
this.state = {
data: [], // <-- there are my objects
isDataEmpty: false,
selectedItemId: ''
}
}
// ... some code
render () {
return (
<View style={styles.container}>
<List
itemList={this.state.data}
onItemPress={ /* go to next screen */}
onItemLongPress={id => {
this.setState({ selectedItemId: this.state.selectedItemId === id ? '' : id })
}}
selectedItemId={this.state.selectedItemId}
/>
</View>
)
}
}
列表组件:
const List = props => {
return (
<FlatList
style={style.itemList}
data={props.itemList}
renderItem={info => (
<ListItem
item={info.item}
selectedItemId={props.selectedItemId}
onItemPress={id => props.onItemPress(id)}
onItemLongPress={id => props.onItemLongPress(id)}
/>
)}
/>
)
}
const areEqual = (previous, next) => {
return next.selectedItemId !== '' && (previous.selectedItemId === next.selectedItemId)
}
export default React.memo(List, areEqual)
列表项组件:
const ListItem = props => {
return (
<TouchableWithoutFeedback
onPress={() => props.onItemPress(props.item.id)}
onLongPress={() => {
props.onItemLongPress(props.item.id)
} }>
<View style={style.listItem}>
<Image resizeMode='cover' source={props.item.image} style={style.image} />
<Text>{props.selectedItemId === props.item.id ? 'XXX' : props.item.name}</Text>
</View>
</TouchableWithoutFeedback>
)
}
const areEqual = (previous, next) => {
return next.selectedItemId && (next.selectedItemId === next.item.id)
}
export default React.memo(ListItem, areEqual)
按下任何项目后,我希望它的名称更改为“XXX”。如果项目将被按下两次,所有项目都应处于正常状态