react modal实现的思路是通过改变display来控制显示与否吗?
还是动态加载modal?
有做过简单的semantic-ui modal的react化,可以参考下
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import $ from 'jquery';
function getInitState() {
return {
visible: false
};
}
export default class Modal extends Component {
constructor(props) {
super(props);
this.state = getInitState();
}
componentDidMount() {
let that = this;
let { eventNamePri } = this.props;
$(window).on(`${eventNamePri}visible`, (ev) => {
that.setState({ visible: true });
});
$(window).on(`${eventNamePri}hidden`, (ev) => {
that.setState(getInitState());
});
// TODO : 可能需要添加resize到window上(函数节流)
}
onResize() {
// 调整大小
let contentDOM = ReactDOM.findDOMNode(this.refs.modalContent);
if (contentDOM) {
$(contentDOM).css('marginTop', ($(contentDOM).height() - $(window).height()) / 2);
}
}
componentDidUpdate(prevProp, prevState) {
if (!prevState.visible && this.state.visible || prevProp.children != this.props.children) {
this.onResize();
}
}
componentWillUnmount() {
let { eventNamePri } = this.props;
$(window).off(`${eventNamePri}visible`);
$(window).off(`${eventNamePri}hidden`);
}
handleClick(ev) {
let { eventNamePri } = this.props;
if (ev.target == ReactDOM.findDOMNode(this.refs.modalPage)) {
$(window).trigger(`${eventNamePri}hidden`);
}
}
render() {
let { visible } = this.state;
let { title } = this.props;
return (
<div className="dimmable scrolling dimmed">
<div ref="modalPage"
className={classnames('ui dimmer modals page transition', {
' visible active ': visible,
' hidden ': !visible
})} onClick={this.handleClick.bind(this)}>
<div ref="modalContent" style={{ fontSize: '14px' }}
className={classnames('ui scrolling modal transition ', {
' visible active ': visible,
' hidden ': !visible
})}>
<div className="ui center aligned header">{title}</div>
<div className="content">
{this.props.children}
</div>
</div>
</div>
</div>
);
}
}
Modal.propTypes = {
// 触发事件的前缀,后面加hidden 代表隐藏, 添加visible代表显示
eventNamePri: PropTypes.string,
title: PropTypes.string
};
Modal.defaultProps = {
eventNamePri: 'modal.',
title: 'modal example'
};
10 回答11.6k 阅读
2 回答3.1k 阅读✓ 已解决
3 回答2.6k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
2 回答2.1k 阅读✓ 已解决
4 回答2.1k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
都可以吧,react-bootstrap 里面是使用显隐的方式的,不过要改成 DOM 实时加载的方式也不困难。显隐的方式需要在
componentWillReceiveProps
里面初始化状态保证再次打开弹窗也是初始化的。如果是动态加载的方式的话倒是没有这个问题,但是如果碰上需要保存状态的情况就 gg 了。所以你可以看情况使用。