简体   繁体   English

如何在React中的数组onClick中显示特定对象?

[英]How do I show a specific object in an array, onClick, in React?

Codesandbox link . Codesandbox链接

I'm trying to accomplish this functionality - when a user clicks on a character on the left, that character's stats will show up on the right. 我正在尝试实现此功能-当用户单击左侧的字符时,该字符的统计信息将显示在右侧。

Currently, I'm pulling in all character information initially using State, in App.js. 当前,我最初在App.js中使用State提取所有字符信息。 Each character is an Object, within a big array. 每个字符都是一个对象,位于一个大数组中。

In /components/content.js, I'm mapping the characters and returning them to the screen. 在/components/content.js中,我正在映射字符并将它们返回到屏幕。 This shows everything. 这显示了一切。

I only want to show each specific character's stats, and only when a user clicks on their specific button on the left. 我只想显示每个特定角色的统计信息,并且仅当用户单击左侧的特定按钮时才显示。

Any thoughts? 有什么想法吗? Thank you for helping! 感谢您的帮助!

Updated code: 更新的代码:

import React, { Component } from 'react';
import Intro from '../intro/intro';

class Content extends Component {
render() {

// Grab the 'characters' object from App.js, and assign it to 'this.props'
const { characters } = this.props;

// Filter the chracters and return only whose 'id' belongs to that of '6'
const filteredCharacters = characters.filter(characters => {
  if (characters.id === 6) {
    return (
      <div className="characters">
        <p>Name: {characters.Name}</p>
        <p>ID: {characters.id}</p>
        <p>Job: {characters.Job}</p>
        <p>Age: {characters.Age}</p>
        <p>Weapon: {characters.Weapon}</p>
        <p>Height: {characters.Height}</p>
        <p>Birthdate: {characters.Birthdate}</p>
        <p>Birthplace: {characters.Birthplace}</p>
        <p>Bloodtype: {characters.Bloodtype}</p>
        <p>Description: {characters.Description}</p>
      </div>
    )
  }
});

// Check to see if it logs properly (it does)
console.log(filteredCharacters);

return (
  <div>
    <section className="content">
      {filteredCharacters}
      {/* <Intro
        title="Final Fantasy 7 Character Stats App"
        text="Search and discover the stats for the main characters of the Final Fantasy 7.">
      </Intro> */}
    </section>
  </div>
)
}
}

export default Content;

Selecting a specific object in the array means filtering the array for that object. 在数组中选择特定对象意味着为该对象过滤数组。 I would recommend the find() , it's like the filter method except that it only returns one result. 我建议使用find() ,它类似于filter方法,除了它只返回一个结果。

You have to decide how you are going to filter the array, as in, according to what characteristics of the object. 您必须根据对象的特征来决定如何过滤数组。

{
    Name: "Cloud Strife",
    Job: "Mercenary",
    Age: 21,
    Weapon: "Sword",
    Height: `5'7`,
    Birthdate: "August 19",
    Birthplace: "Nibelheim",
    Bloodtype: "AB",
    Description: `something something`
  }

Most of your fields are unique so you could use pretty much any field. 您的大多数字段都是唯一的,因此您几乎可以使用任何字段。 However they are unique by accident, you could get two character with the same height or name. 但是,它们偶然是唯一的,您可以得到两个具有相同高度或名称的字符。 I recommend adding a new key that is always unique. 我建议添加一个始终唯一的新密钥。 The simplest way to do that is to give it a timestamp of the moment it was created. 最简单的方法是给它创建日期的时间戳。

I would also recommend creating a new field in state like selectedCharacter , in the on click handler you then take your array and filter it down to the clicked character charactersArray.find(character => chacter.id === selected.id) . 我还建议您创建状态为selectedCharacter的新字段,在单击处理程序中,然后获取数组并将其过滤为单击的字符charactersArray.find(character => chacter.id === selected.id) Where selected.id comes from passing the object of the character you click on into the onClick handler. 其中的selected.id来自将您单击的字符的对象传递给onClick处理程序。

You then reference the state value of selectedCharacter in your individual character component not the whole array, this will always show the last character clicked on. 然后,您在单个字符组件中而不是整个数组中引用selectedCharacter的状态值,这将始终显示最后一次单击的字符。

Here you go, replace your Content class component with this: 在这里,您可以用以下内容替换Content类组件:

  const Content = ({ characters }) => {

  // pick out the character you want by id
  const character = characters.find(character => character.id === 6);

  return (
    <div className="characters" key={character.id}>
      <p>Name: {character.Name}</p>
      <p>ID: {character.id}</p>
      <p>Job: {character.Job}</p>
      <p>Age: {character.Age}</p>
      <p>Weapon: {character.Weapon}</p>
      <p>Height: {character.Height}</p>
      <p>Birthdate: {character.Birthdate}</p>
      <p>Birthplace: {character.Birthplace}</p>
      <p>Bloodtype: {character.Bloodtype}</p>
      <p>Description: {character.Description}</p>
    </div>
  );
};

I used find() instead of filter() because filter will map over the entire array whereas find will stop when it finds the result you want. 我使用find()而不是filter(),因为filter会映射到整个数组,而find会在找到所需结果时停止。 Otherwise, it is exactly the same, just a better fit when you only want one result. 否则,它是完全相同的,当您只想要一个结果时,它才是更好的选择。

I also switched from a class component to a stateless functional component since you are not using any of the classes lifecycle methods. 由于您没有使用任何类生命周期方法,因此我也从类组件切换为无状态功能组件。

You really want to be passing in the id selected and not hard coding it, but I didn't change that so that it was less confusing. 您确实想传递选择的ID,而不是对其进行硬编码,但是我没有更改它,以减少混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 中使用 onClick 重置 state 的特定部分 - How do I reset a specific part of a state with onClick in React 反应:如何映射对象数组,然后onclick将一个状态单独添加到另一个数组中? - REACT: How do I map through array of objects, then onclick add an individually to another array in state? 如何在React Native中的数组对象中呈现数组 - How do I render an array within an object of array in React Native 如何在 React 中使用 Onclick 显示 html 过滤器/映射数组 - How to show html filter/map array with Onclick in React 如何使用 React 更新键数组中的特定键 - How do I update a specific key in an array of keys using React Javascript:如何在我的阵列中使用特定键删除 object? - Javascript: How do I remove an object with a specific key in my array? 如何从 MongoDB 的数组中找到并显示特定的 object? - How do I find and display a specific object from an array in MongoDB? 如何在javascript中替换数组中的特定对象? - How do I replace a specific object in an array in javascript? 如何在特定时间间隔后在 react.js 中显示每个数组 object? - How to show every array object in react.js after specific time interval? 如何使用 useState object 数组在 React 中添加 HTML 元素 onClick? - How to add HTML element onClick in React with a useState object array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM