鍍金池/ 問答/HTML/ React + Antd 如何抽離出一個Modal組件?

React + Antd 如何抽離出一個Modal組件?

后端開發(fā),對前端不是很熟悉,現(xiàn)在期望能把一個Modal框抽出來復用。

因為某個Modal很通用,會出現(xiàn)在很多的頁面上,現(xiàn)在想把它抽成一個單獨的js,在使用的地方引入進來使用,不知道可不可行?

具體該怎么做呢?state可以取到嗎在這個modal中?

更新:看了 @二麗 的回答后,自己揣摩著寫了這么個demo,基本可以實現(xiàn)點擊button控制modal了,但是現(xiàn)在遇到一個問題,打開Modal后,我在頁面中任意位置點擊,都會造成Modal的隱藏,不知道這是什么原因?【打了個log,發(fā)現(xiàn)頁面任意位置點擊都觸發(fā)了cancel方法,不知道這是什么緣故?】

clipboard.png

父組件

import React, { Component } from 'react';
import './App.css';
import Button from 'antd/lib/button';
import MyModal from './component/MyModal'

class App extends Component {
  constructor() {
    super();
    this.state = {
      visible: false,
      title: '子組件',
      key: Math.random()
    }
  }

  onCancel = () => {
    console.log('cancel');
    this.setState({
      visible: false,
      key: Math.random()
    });
  }

  showModel = () => {
    let visible = this.state.visible;
    this.setState({
      visible: !visible
    })
  }

  render() {
    return (
      <div className="App">
        <Button type="primary"
          onClick={this.showModel}>
          Button
        </Button>
        <MyModal
          key={this.state.key}
          visible={this.state.visible}
          title={this.state.title}
          onCancel={this.onCancel}>
        </MyModal>
      </div>
    );
  }
}

export default App;

子組件

import React, { Component } from 'react';
import { Modal } from 'antd';
export default class MyModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }
    handleOk = (e) => {
        console.log(e);
    }

    handleCancel = (e) => {
        console.log('cancel');
        this.props.onCancel();
    }
    render() {
        return (
            <Modal
                key={Math.random()}
                title={this.props.title}
                visible={this.props.visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>Some contents...</p>
                <p>Some contents...</p>
                <p>Some contents...</p>
            </Modal>
        )
    }
}
回答
編輯回答
青黛色

請仔細看文檔,Modal api中有個maskClosable 表示點擊蒙層是否允許關閉,默認是true。
不想點擊蒙層關閉可設置,maskClosable = {false}

2017年10月17日 22:48
編輯回答
念舊
import React, { Component } from 'react';
import { Modal } from 'antd';
export default class Model extends Component {
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
    this.props.onCancle();
  }
  render() {
    let {children,visible,width,title}=this.props;
    return (
      <Modal 
        title={title}
        visible={visible}
        width={width}
        destroyOnClose={true}
        onCancel={this.handleCancel}
        footer={null}
        className={styles.modal}
      >
        {children}
      </Modal>
    )
  }
}
2018年2月4日 19:46