React js 如何显示点击的 div 和删除之前的 div 内容

React js how to show clicked div and delete previous div content

你好,我有一个问题,是否有人可以提供帮助。

当我点击代码显示和隐藏文本的每个按钮时,我创建了一个带有树按钮的 React 应用程序。

但是我希望当我点击例如按钮 2 时,按钮 1 和 3 的文本被隐藏。如果我点击按钮 3,按钮 1 和 2 中的文本也会被隐藏。


import React, { useState } from 'react';

export default class Tinfo extends React.Component{
    constructor(props){
       super(props);
       this.state = { show: new Array(3).fill(false) };
       this.baseState = this.state 
    }

    resetState = () => {
        this.setState(this.baseState)
      }

    toggleDiv = (index) => {
       var clone = Object.assign( {}, this.state.show );
       switch(clone[index]){
          case false:
          clone[index] = true
             break;
          case true:
             clone[index] = false
             break;
       }
       this.setState({ show: clone });
    }



    render(){
       return(
     <div>
          { this.state.show[0] && <div id="tinfo"> First Div </div>}
          { this.state.show[1] && <div id="tinfo"> Second Div </div>}
          { this.state.show[2] && <div id="tinfo"> Third Div </div> }
          <button onClick={() => this.toggleDiv(0)}>button 1</button> 
          <button onClick={() => this.toggleDiv(1)}>button 2</button>
          <button onClick={() => this.toggleDiv(2)}>button 3</button>
     </div>

       )
    }
 }


既然只能显示一个,那就重置一下状态吧

toggleDiv = index => {
  const show = new Array(3).fill(false);
  show[index] = true;
  this.setState({
    show
  });
}

虽然它现在应该命名为 showDiv 因为它设置状态并隐藏其余部分,但它不是切换。