React
HTML
<div id="root"></div>
CSS
html, body {
margin: 0;
padding: 0 15px;
}
React
class Window extends React.Component {
constructor(props) {
super(props);
this.state = { win: null, el: null };
}
componentDidMount() {
let win = window.open("", "", "width=600,height=400");
win.document.title = "A React portal window";
let el = document.createElement("div");
win.document.body.appendChild(el);
this.setState({ win, el });
}
componentWillUnmount() {
this.state.win.close();
}
render() {
const { el } = this.state;
if (!el) {
return null;
}
return ReactDOM.createPortal(this.props.children, el);
}
}
class MouseMoveTest extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.handleDrag = this.handleDrag.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.unbindEventListeners = this.unbindEventListeners.bind(this);
}
handleDrag(e) {
this.setState(state => ({ count: state.count + 1 }));
}
handleMouseDown(e) {
e.preventDefault();
this.handleDrag(e);
window.addEventListener("mousemove", this.handleDrag);
window.addEventListener("mouseup", this.handleMouseUp);
}
handleMouseUp() {
this.unbindEventListeners();
}
unbindEventListeners() {
window.removeEventListener("mousemove", this.handleDrag);
window.removeEventListener("mouseup", this.handleMouseUp);
}
render() {
return (
<div
style={{ width: "100px", height: "100px", backgroundColor: "red" }}
onMouseDown={this.handleMouseDown}
>
{this.state.count}
</div>
);
}
}
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.onClick = this.onClick.bind(this);
}
onClick(e) {
this.setState(state => ({ count: state.count + 1 }));
this.props.onClick && this.props.onClick();
}
render() {
...