reactjs 我怎样才能把一个按钮变成塌陷呢?

e4yzc0pl  于 2022-11-29  发布在  React
关注(0)|答案(3)|浏览(199)

我想把一个按钮变成一个collapse,我使用的是collapse的antd,那个新按钮不应该打开或者关闭collapse,我想给予她其他的功能呢?

const {  Collapse, Button  } = antd;
const { Panel } = Collapse;

function callback(key) {
  console.log(key);
}

const text = ` hi `;

ReactDOM.render(
  <Collapse 

  defaultActiveKey={['1']} onChange={callback}>
    <Panel header={<Button type="primary">Primary Button</Button>} key="1" >
    <Button type="link">My button</Button>  > 
      <p>{text}</p>
    </Panel>
  </Collapse>,
  mountNode,
);

为什么单击该按钮时会打开COLLAPSE?我不希望打开COLLAPSE

vxqlmq5t

vxqlmq5t1#

我猜你不想打开折叠的按钮是Panel标题中的Primary Button,要做到这一点,你必须手动控制activeKey,并检查当用户点击面板标题时,他们点击的是Primary Button还是它的外部。
试试这个:

import React, { useState, useRef } from "react";
import * as antd from "antd";

const { Collapse, Button } = antd;
const { Panel } = Collapse;

const text = ` hi `;
export const App = () => {
  const [activeKey, setActiveKey] = useState(0);
  const isButtonClicked = useRef(false);

  const callback = key => {
    console.log(key, isButtonClicked.current);
    // Check if use click on the button don not update activekey
    if (
      isButtonClicked &&
      isButtonClicked.current &&
      isButtonClicked.current === true
    ) {
      isButtonClicked.current = false;
      return;
    }

    if (!activeKey) {
      setActiveKey(key);
    } else {
      setActiveKey(0);
    }
  };
  return (
    <Collapse activeKey={activeKey} onChange={callback}>
      <Panel
        header={
          <Button
            onClick={() => {
              // set the isButtonClicked ref to tru when user click on Button
              isButtonClicked.current = true;
              // Do other functionality you want for this button here
            }}
            type="primary"
          >
            Primary Button
          </Button>
        }
        key="1"
      >
        <Button type="link">My button</Button> ><p>{text}</p>
      </Panel>
    </Collapse>
  );
};

我创建了一个codesandbox来演示它

yuvru6vn

yuvru6vn2#

试试这个:

const {  Collapse, Button  } = antd;
const { Panel } = Collapse;

function callback(key) {
  console.log(key);
}

const text = ` hi `;

ReactDOM.render(
  <Collapse  defaultActiveKey={['1']} onChange={callback}>
    <Panel header={<Button type="primary">Primary Button</Button>} key="1" > 
       <Button type="link">My button</Button> 
      <p>{text}</p>
    </Panel>
  </Collapse>,
  mountNode,
);
guykilcj

guykilcj3#

如果您希望按钮位于面板内,则按钮代码应位于面板内,而不是位于其标记内..而不是:

<Panel header="This is panel header 1" key="1" 
<Button type="link">My button</Button>  > 

  <p>{text}</p>
</Panel>

这应当

<Panel header="This is panel header 1" key="1">
    <Button type="link">My button</Button>
    <p>{text}</p>
</Panel>

相关问题