【发布时间】: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;
【问题讨论】:
-
这个组件应该被命名为
Users,你应该创建一个名为User的子组件,并把显示细节的逻辑移到那里
标签: javascript reactjs api