React - Render Item inside map function by click event

China☆狼群 提交于 2021-02-18 03:22:19

问题


let say i have an array with two items i want to make a click event that will show some content for the specific index i clicked

for example :

let array = [
  {name:test},
  {name:test2}
]

this.array.map((item,index)=>{

   return(

      <div>
        {item.name}
         <button onClick={()=>this.showContentFunction()} >show content</button>
         {this.renderContent()}
      </div>

   )

})

now it will show two items i want to click on the first item button and showing the hidden content only under the same item index and not for all the items

how can i do that

thanks alot !


回答1:


<button onClick={() => this.showContent(index)}>Show Content</button>

This is the general idea. You need to pass the index of the item to your click handler. In your click handler, you can either do something which will edit the items in the array themselves, setting a showContent boolean as one of their properties, and then use it like this...

this.array.map((item, index) => {
   return (
      <div>
         {item.name}
         <button onClick={() => this.showContent(index)}>Show Content</button>
         {item.showContent &&
            this.renderContent()
         }
      </div>
   );
})

...or you can maintain a mapping from item ID to content visibility, and reference it when rendering:

constructor(props) {
  super(props);

  this.state = {
    isItemContentVisible: {}
  };
}

showContent(id) {
  // merge new value with existing visibility status into new object
  this.setState({
    isItemContentVisible: {     
      ...this.state.isItemContentVisible,
      [id]: true
    }
  });
}

// ...and when you're rendering the list...
this.array.map((item, index) => {
   return (
      <div>
         {item.name}
         <button onClick={() => this.showContent(item.id)}>Show Content</button>
         {this.state.isItemContentVisible[item.id] &&
            this.renderContent()
         }
      </div>
   );
})


来源:https://stackoverflow.com/questions/45779445/react-render-item-inside-map-function-by-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!