根据ID隐藏元素

时间:2019-11-13 13:08:00

标签: react-native

我想单击一个项目,该项目将被隐藏。我尝试了这段代码,但是所有元素都隐藏在数组中。那么如何根据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>

1 个答案:

答案 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>
    )
  }
}