【问题标题】:show/hide Custom component in react在反应中显示/隐藏自定义组件
【发布时间】: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 详细信息。

【问题讨论】:

  • 一种可能的解决方案是:不要在每个组件中维护 showComponent bool,而是在 todo 组件的父级中维护它,并将 function 也从父级传递给 todo 并从 todo 调用 function要更改父级中的state,使用该布尔值显示用户信息,任何用户的onClick,重置父级中的所有值并为该特定组件设置为true,它将起作用。

标签: reactjs react-native react-router repeater show-hide


【解决方案1】:

你可以使用这个语法

{showComponent && <div></div>}

基于 showComponent 值,您可以显示隐藏 div,也可以通过 setState

更新该值

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多