我有一个应用程序,我正在构建一个用户列表。我已经通过用户数组进行了映射,并且能够显示每个用户的名称,以便可以点击它。然后我将道具传递给用户卡"组件应该在哪个组件中呈现用户的信息。这种情况发生得很独特,工作得很好,但是用户正在显示4次(阵列的长度)
import React, {Component} from 'react';
import UserCard from './UserCard.jsx';
class User extends Component{
onClick(e){
e.preventDefault();
const {updateUserId, user} = this.props;
updateUserId(user);
}
render(){
const {user, activeUser, userIdToShow} = this.props;
const active = user === activeUser ? 'active' : '';
return(
<li className={active} role='presentation'>
<a onClick={() => this.props.updateUserId(this.props.users.Id)}>
{this.props.users.Name}
</a>
{userIdToShow ? <UserCard
key={this.props.users.Id}
user={this.props.People[userIdToShow-1]}/> : null}
</li>
)
}
}
export default User;
用户列表(父级用户)看起来像这样:
import React, {Component} from 'react';
import User from './User.jsx';
class UserList extends Component{
render(){
return(
<ul className='nav nav-tabs nav-justified'>
{this.props.People.map(person => {
return <User
users={person}
key={person.Id}
{...this.props}
/>
})}
</ul>
)
}
}
export default UserList;
任何反馈都将不胜感激。我会尝试在JSBin或Fiddle上获取我的应用程序。提前谢谢!
答案 0 :(得分:1)
你可以试试这个:
class User extends Component{
// 1. use a state to show/hide user
constructor(props){
super(props);
this.state = {show:false};
}
// 2. add a show user that will be called in on-click
showUser(){
this.setState({show:true});
}
return(
<li className={active} role='presentation'>
// 3. update the state of show in on-click
<a onClick={() => this.props.updateUserId(this.props.users.Id);this.showUser();}>
{this.props.users.Name}
</a>
// 4. use state to display the user card
{this.state.show ? <UserCard
key={this.props.users.Id}
user={this.props.People[userIdToShow-1]}/> : null}
</li>
)
}
}
答案 1 :(得分:0)
我通过简单地对我的代码执行以下操作解决了这个问题:
return(
<li className={active} role='presentation'>
<a onClick={() => this.props.updateUserId(this.props.users.Id)}>
{this.props.users.Name}
</a>
{userIdToShow ((I had no check against the "Clicked on User's ID here))? <UserCard
key={this.props.users.Id}
user={this.props.People[userIdToShow-1]}/> : null}
</li>
)
因为我没有检查,它会使卡片呈现四次,并且具有相同的属性。我需要这样做
return(
<li className={active} role='presentation'>
<a onClick={() => this.props.updateUserId(this.props.users.Id)}>
{this.props.users.Name}
</a>
{userIdToShow === this.users.props.Id ? <UserCard
key={this.props.users.Id}
user={this.props.People[userIdToShow-1]}/> : null}
</li>
)
这就像一个魅力。