React:如果组件不相关,如何调用模态

时间:2018-05-07 01:50:00

标签: javascript reactjs modal-dialog components

我正在尝试启动模式,但是,使用当前设置,组件没有父子关系并且完全不相关。有没有办法做到这一点?我知道理想的是将它们放在亲子设置中,但这种情况要求它们不相关。我需要App.js中的两个按钮才能启动模态,就像Modal.js中的按钮一样。任何帮助或想法将不胜感激。

App.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import InputComponent from './components/input_component';
import Modal from './components/modal';


class App extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount(){
    this.refs.modal.showFunction();
    this.refs.modal.hideFunction();
  }

  state = {
    fields: {},
  };

  onChange = updatedValue => {
    this.setState({
      fields: {
        ...this.state.fields,
        ...updatedValue,
      }
    });
};
  render() {
    return (
      <div> 
        <InputComponent onChange={fields => this.onChange(fields)}/>
        <p>{JSON.stringify(this.state.fields)}</p>
        <Modal container={this} ref="modal" />
        <button onClick={this.showFunction}>click to trigger show modal from App</button>
        <button onClick={this.hideFunction}>click to trigger hide modal from App</button>
      </div>
    );
  }
}

export default App;

Modal.js:

import React from 'react';

import '../styles/styles.css';

export default class Modal extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      show: false,
    }
    this.showFunction = this.showFunction.bind(this);
    this.hideFunction = this.hideFunction.bind(this);
  }

  showFunction(){
    this.setState({
      show: true,
    })
  }

  hideFunction(){
    this.setState({
      show: false,
    })
  }

  render(){ 
    if(!this.state.show){
      return <button onClick={this.showFunction}>showModal</button>
    }
    return(
        <div className="modal-styles">
          <Modal show={this.state.show} container={this.props.container}>
            <h2>This will be the Modal</h2>
          </Modal>
          <button onClick={this.hideFunction}>hideModal</button>
        </div>
      );
  }
}

1 个答案:

答案 0 :(得分:2)

如果两个组件来自两个完全独立的位置,这可能是一个边缘情况,只使用window变量是最实用的。请注意,此处的/* GLOBAL window.etc */语法不适用于ESLint,仅为了清晰起见。

<强> App.js

/* GLOBAL window.__showModal */
/* GLOBAL window.__hideModal */

// class App...

  showFunction() {
    if (window.__showModal) {
      window.__showModal();
    } else {
      // Handle errors: Other component has not mounted
    }
  }

  hideFunction() {
    if (window.__hideModal) {
      window.__hideModal();
    } else {
      // Handle errors: Other component has not mounted
    }
  }

<强> Modal.js

/* GLOBAL window.__showModal */
/* GLOBAL window.__hideModal */

// class Modal...

  componentDidMount() {
    window.__showModal = () => this.showFunction()
    window.__hideModal = () => this.hideFunction()
  }

  componentDidUnmount() {
    // Kill references to 'this'
    window.__showModal = undefined
    window.__hideModal = undefined
  }