ReactJS:使用react钩子显示/隐藏具有不同ID的不同div

时间:2019-07-17 06:35:46

标签: reactjs react-native frontend react-hooks

我的项目中有一个功能,其中有多个显示div的图标。

到目前为止,这是我的代码:

  const [drawerOpen, setDrawerOpen] = useState(false);
    const [click, setClick] = useState(false);

    const contextData = {
        stateSetters: {
            setDrawerOpen
        }
    };

<Row>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
    setClick(!click);
    contextData.stateSetters.setDrawerOpen(!click);
      }}/>
   </div>
  </Card>
 </Col>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
    setClick(!click);
    contextData.stateSetters.setDrawerOpen(!click);
      }}/>
   </div>
  </Card>
 </Col>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
    setClick(!click);
    contextData.stateSetters.setDrawerOpen(!click);
      }}/>
   </div>
  </Card>
 </Col>
</Row>

<div className={drawerOpen ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-1">

   </div>
</div>
<div className={drawerOpen ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-2">

   </div>
</div>
<div className={drawerOpen ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-3">

   </div>
</div>

我正在寻找有关如何通过调用其div ID进行打开的方法。我尝试调整onClick(),但它仍会立即打开所有div。

1 个答案:

答案 0 :(得分:1)

您需要指定要打开的抽屉ID,而不是状态中的布尔值

const [drawerOpen, setDrawerOpen] = useState('');
const handleDrawerOpen = (data) => {
    if(data === drawerOpen) {
        setDrawerOpen('');
    } else {
        setDrawerOpen(data);
    }
}
    const contextData = {
        stateSetters: {
            setDrawerOpen: handleDrawerOpen
        }
    };

<Row>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
        contextData.stateSetters.setDrawerOpen('data-1');
      }}/>
   </div>
  </Card>
 </Col>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
         contextData.stateSetters.setDrawerOpen('data-2');
      }}/>
   </div>
  </Card>
 </Col>
<Col md={8}>
 <Card className="project-card">
   <div>
     <Icon type="down" onClick={() => {
          contextData.stateSetters.setDrawerOpen('data-3');
      }}/>
   </div>
  </Card>
 </Col>
</Row>

<div className={drawerOpen === 'data-1' ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-1">

   </div>
</div>
<div className={drawerOpen === 'data-2' ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-2">

   </div>
</div>
<div className={drawerOpen === 'data-3' ? 'show-feature-drawer' : 'hide-feature-drawer'}>
   <div className="feature-drawer" id="data-3">

   </div>
</div>