【问题标题】:How do I change only the individual div of the onClick function to display more information?如何仅更改 onClick 函数的单个 div 以显示更多信息?
【发布时间】:2019-11-04 23:56:25
【问题描述】:

我正在尝试创建一个功能,当单击“详细信息”按钮时显示有关用户的更多详细信息。但是,按钮会更改每个 div 类的状态。我想将此限制为仅影响包含“详细信息”按钮的 div。我附上了一张带有基本样式的屏幕截图。我非常感谢任何其他反馈,因为我是 React 的新手。

import React, {Component} from 'react';
import './App.css';

class User extends Component {
  constructor(props) {
    super(props);
    this.state = { isVerified: false, users: []}
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch ('https://randomuser.me/api?results=50')
    .then(response => response.json())
    .then(parsedJSON => parsedJSON.results.map(contact => (
      {
        id: `${contact.login.uuid}`,
        username: `${contact.login.username}`,
        firstname: `${contact.name.first}`,
        lastname: `${contact.name.last}`,
        pic: `${contact.picture.thumbnail}`,
        phone: `${contact.cell}`,
        city: `${contact.location.city}`,
        lat: `${contact.location.coordinates.latitude}`,
        long: `${contact.location.coordinates.longitude}`
      }
    )))
    .then(users => this.setState(
      {
        users,
        isVerified: false,
        viewDetails: false
      }
    ))
    .catch(error => console.log("parsing failed", error))
  }

//This is the  method that's changing state and showing details for every random user/profile div
  viewUserDetails = () => {
    console.log('view details toggle button here')
    this.setState({showDetails: !this.showDetails})
  }

  render() { 
    const {isVerified, users, showDetails} = this.state;
    return ( 
      <div>
        <header>
          <h1>Your Contacts</h1><br></br>
          Verify Friends for Offline Use
          </header>
          <div className="container">
            {users.map(userInfo => {
              const {id, username, firstname, lastname, pic, phone, city, lat, long} = userInfo;
              return (
                <div key={userInfo.id} title={userInfo.username} className="user-profile">
                  {!this.state.showDetails ? (
                  <div className="basic-userInfo">
                    {firstname} {lastname}
                    <img src={pic} alt={username} className="user-thumbnail-basic"></img>
                    <button className="details-button" onClick={this.viewUserDetails}>Details</button>
                  </div>
                  ) : (
                  <div className="detailed-userInfo">
                    {firstname} {lastname}
                    <img src={pic} alt={username} className="user-thumbnail-detailed"></img>
                    <ul>
                      <li>{username}</li>
                      <li>{phone}</li>
                      <li>{city}</li>
                    </ul>
                  </div>
                  )}
                </div>
              )
            })}
          </div>
      </div>
     );
  }
}

export default User;

preview before details button is clicked

【问题讨论】:

  • 这个组件应该被命名为Users,你应该创建一个名为User的子组件,并把显示细节的逻辑移到那里

标签: javascript reactjs api


【解决方案1】:

您现在使用状态的方式无法实现您想要的。您没有以任何方式将 showDetails 状态限定为用户。如果您想将其范围限定为单个用户,您可以为您的按钮提供一个 id 属性,即用户的 id, 像这样:

                    &lt;button id={user.id} className="details-button" onClick={this.viewUserDetails}&gt;Details&lt;/button&gt;

然后,您可以将点击事件传递给您的 viewUserDetails 函数,而不是将 showDetails 存储为布尔值,您可以将其设为用户 ID,如下所示:

viewUserDetails = event => {
    console.log('view details toggle button here')
    this.setState({showDetails: event.target.id})
  }

然后,不是检查 showDetails 是否为真,而是检查它是否等于用户的 id:

                  ...
                  {this.state.showDetails !== id ? (

当然,这只会让您一次查看一位用户的详细信息。如果您希望能够查看任意数量用户的详细信息,则可以将 showDetails 存储为 id 数组,并检查它是否 .includes() 用户的 id。

【讨论】:

    【解决方案2】:

    创建一个 user 子组件,它有自己的showDetails 状态,然后将 Users 映射到该子组件。

    这是一个沙盒,你可以玩一下,请阅读代码说明,祝你好运! - https://codesandbox.io/s/condescending-cache-wdeyv

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多