我想单击一个项目,该项目将被隐藏。我尝试了这段代码,但是所有元素都隐藏在数组中。那么如何根据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>
答案 0 :(得分:1)
如果要在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>
)
}
}