在可折叠内部显示组件

时间:2019-07-08 03:10:06

标签: javascript reactjs jsx antd

您好,当用户单击表单图标时,我试图在“ antd”可折叠框中显示一个表单组件,该表单组件应出现在已折叠文本下方的可折叠内部

我正在使用可折叠的antd库

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import { Collapse, Icon } from 'antd';
import Form from './Form';

const { Panel } = Collapse;

const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;

const genExtra = () => (
  <Icon
    type="form"
    onClick={event => {
      // If you don't want click extra trigger collapse, you can prevent this:
      event.stopPropagation();

      console.log('You have click on edit form');
    }}
  />
);

const customPanelStyle = {
  background: '#f7f7f7',
  borderRadius: 4,
  marginBottom: 24,
  border: 0,
  overflow: 'hidden',
};

ReactDOM.render(
  <Collapse
    bordered={false}
    defaultActiveKey={['1']}
    expandIcon={({ isActive }) => <Icon type="caret-right" rotate={isActive ? 90 : 0} />}
  >
    <Panel 
      header="This is panel header 1" 
      key="1" style={customPanelStyle}
      extra={genExtra()}
    >
      <p>{text}</p>
    </Panel>
  </Collapse>,
  document.getElementById('container'),
);

这是表单组件:

import React from 'react';

const Form = () => {
  return(
    <div id="wrapper">
      <div className="group">
        <label for="name">Name</label>
        <input type="text" id="name" />
      </div>
      <hr/>
      <div className="group">
        <label for="email">Email</label>
        <input type="email" id="email" />
      </div>
    </div>
  );
}

export default Form;

- 我只希望当用户单击标题中的小图标时,Form Component出现在可折叠的内部,我将留下指向stackblitz的链接:https://stackblitz.com/edit/react-pkffgm

1 个答案:

答案 0 :(得分:1)

您需要将Collapsible移至另一个基于类的组件,在那里您可以有状态显示/隐藏Form组件,

在新构建的基于类的组件中,您需要保持状态,

constructor(props){
    super(props);
    this.state ={
      showForm: false
    }
}

然后在渲染中,您可以像这样显示Form

<Panel 
      header="This is panel header 1" 
      key="1" style={customPanelStyle}
      extra={this.genExtra()}
>
      <p>{text}</p>
      {this.state.showForm && <Form />}
</Panel>

最后,点击表单编辑图标,您需要更改showForm的状态,

genExtra = () => (
  <Icon
    type="form"
    onClick={event => {
      // If you don't want click extra trigger collapse, you can prevent this:
      event.stopPropagation();
      this.setState({showForm: true})
      console.log('You have click on edit form');
    }}
  />
);

注意:在Form组件中,您会收到lable的警告,

<label htmlFor="name">Name</label> //instead of `for` attribute in react we have `htmlFor` attribute.

Demo