后端开发,对前端不是很熟悉,现在期望能把一个Modal框抽出来复用。
因为某个Modal很通用,会出现在很多的页面上,现在想把它抽成一个单独的js,在使用的地方引入进来使用,不知道可不可行?
具体该怎么做呢?state可以取到吗在这个modal中?
更新:看了 @二丽 的回答后,自己揣摩着写了这么个demo,基本可以实现点击button控制modal了,但是现在遇到一个问题,打开Modal后,我在页面中任意位置点击,都会造成Modal的隐藏,不知道这是什么原因?【打了个log,发现页面任意位置点击都触发了cancel方法,不知道这是什么缘故?】
父组件
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>
)
}
}