根据ID隐藏元素



我想点击按钮一个项目,它将被隐藏。我尝试过这个代码,但所有元素都隐藏在数组中。那么如何根据item.post_id进行隐藏呢?

this.state = {
hide::true
};
hide = () => {
this.setState({
hide:false
})
}
render() {
return (
<View>
{this.state.post.results.map((item, key) => {
<View>
{this.state.hide && (
<>
<View
key={key}
> 
<Text>{item.title}</Text>
<Text style={{ marginVertical: 10 }}>{item.text}</Text>
<Button title="Hide" hide={this.hide} />
</View>
</>
)}
</View>
)
})}
</View>

如果你在post.results上进行映射,那么你应该隐藏一个基于id而不是布尔值的按钮。否则你会把所有的按钮都藏起来。

我认为这就是你想要实现的目标:

import React, { Component } from 'react'
export default class UntitledComponent extends Component {
state = {
hiddenObject: null
};
hideButton = (key) => {
this.setState({
hiddenObject: key
})
}
render() {
return (
<View>
{this.state.post.results.map((item, key) => {
// Only show when this key is not hidden
this.state.hiddenObject !== key && (
<View key={key}>
<Text>{item.title}</Text>
<Text style={{ marginVertical: 10 }}>{item.text}</Text>
{/* NOTE: always bind to events:  () => this.hideButton(key) */}
<Button onClick={() => this.hideButton(key)}>Hide</Button>
</View>
)
})}
</View>
)
}
}

最新更新