单击 React 在新窗口中打开组件

新手上路,请多包涵

我有一个显示数据的组件。我必须在单击父组件的按钮/链接时在新窗口中打开此组件。

 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>
        )
    }
}

我不知道如何调用另一个组件并将其显示在新的指定大小的窗口中。

实际上我需要向那个子组件发送一个道具,它会用它从数据库中获取数据并呈现它。

原文由 Vandhana 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 545
1 个回答

您可以使用 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();
  }
}

原文由 CD.. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题