gpt4 book ai didi

javascript - react : How to invoke a modal if components are unrelated

转载 作者:行者123 更新时间:2023-11-29 10:59:25 25 4
gpt4 key购买 nike

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

应用程序.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;

模态.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>
);
}
}

最佳答案

如果这两个组件来自两个完全不同的地方,这可能是一种边缘情况,在这种情况下,最实际的做法是只使用 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
}

关于javascript - react : How to invoke a modal if components are unrelated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com