在点击响应中打开新窗口中的组件 [英] Open a component in new window on a click in react
本文介绍了在点击响应中打开新窗口中的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个显示数据的组件。我必须在新窗口中单击父组件的按钮/链接打开此组件。
I have a component which displays a data. I have to open this component in a new window on clicking a button/ link from a parent component.
export default class Parent extends Component {
construtor(props) {
super(props);
}
viewData = () => {
window.open('childcomponent.js','Data','height=250,width=250');
}
render() {
return (
<div> <a onclick={this.viewData}>View Data</a></div>
)
}
}
我不知道如何调用另一个组件并将其显示在指定的新大小窗口中。
I dont know how to invoke another component and also display it in a new size specified window.
实际上我需要向该子组件发送一个道具,用它从数据库中获取数据并渲染它。
Actually I need to send a props to that child component with which it will fetch me the data from database and render it.
推荐答案
您可以使用 ReactDOM .createPortal
在新窗口中呈现组件 David Gilbertson 在他的发布:
class MyWindowPortal extends React.PureComponent {
constructor(props) {
super(props);
// STEP 1: create a container <div>
this.containerEl = document.createElement('div');
this.externalWindow = null;
}
render() {
// STEP 2: append props.children to the container <div> that isn't mounted anywhere yet
return ReactDOM.createPortal(this.props.children, this.containerEl);
}
componentDidMount() {
// STEP 3: open a new browser window and store a reference to it
this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');
// STEP 4: append the container <div> (that has props.children appended to it) to the body of the new window
this.externalWindow.document.body.appendChild(this.containerEl);
}
componentWillUnmount() {
// STEP 5: This will fire when this.state.showWindowPortal in the parent component becomes false
// So we tidy up by closing the window
this.externalWindow.close();
}
}
这篇关于在点击响应中打开新窗口中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文