【发布时间】:2017-05-03 07:02:50
【问题描述】:
我试图在点击时显示用户详细信息,在点击其他用户详细信息时我想隐藏或删除页面上现有的用户详细信息,下面是我的一段代码
TODO.js
import React from "react";
import {fetchjson} from '../../helpers/helpers';
import Userdetail from "../../components/userdetails/userdetail";
export default class Todo extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
userData: []
};
}
handleClick = () => {
fetchjson('users/' + this.props.tododdate.userid).then((data) => {
console.log(data)
this.setState({
showComponent: true,
userData: data
});
});
}
render() {
const thistodo = this.props.tododdate;
return ( <div className = "row" >
<div className = "col-md-6" >
<h3 onClick = {this.handleClick} > USER ID: {thistodo.userid } </h3>
<ul className = "list-unstyled" > {
thistodo.todo.map(todo =>
<li > < input type = "checkbox"
checked = {
todo.completed
}
/> {todo.title}</li >
)
} </ul> </div>
<div className = "col-md-6" > {
this.state.showComponent ?
<Userdetail userprops = {
this.state.userData
}/> :
null
} </div> </div>
)
}
}
UserDetail.js
import React from "react";
export default class Userdetail extends React.Component{
render() {
const thisuserdata=this.props.userprops;
return (
<div>
<label>name : </label>
{thisuserdata.name}<br/>
<label>username : </label>
{thisuserdata.username}<br/>
<label>name : </label>
{thisuserdata.name}<br/>
<label>phone : </label>
{thisuserdata.phone}<br/>
<label>website : </label>
{thisuserdata.website}<br/>
</div>
)}
}
当我点击用户 ID:1/用户 ID:2... 时,我可以显示用户详细信息,但我想在点击用户 ID:2 详细信息时隐藏用户 ID:1 详细信息。
【问题讨论】:
-
一种可能的解决方案是:不要在每个组件中维护
showComponentbool,而是在 todo 组件的父级中维护它,并将function也从父级传递给 todo 并从 todo 调用function要更改父级中的state,使用该布尔值显示用户信息,任何用户的onClick,重置父级中的所有值并为该特定组件设置为true,它将起作用。
标签: reactjs react-native react-router repeater show-hide