gpt4 book ai didi

javascript - 如何在 react 中切换模态并传递子 Prop ?

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

在这个简单的模式中,我只想切换一条消息。我几乎有了它,但我错过了如何传递子 Prop 消息,并且显示按钮正在关闭模态而不是关闭按钮。有人可以解释解决方案和上下文细节吗?

这是我的代码和一个指向 code sandbox 的链接App.js

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Modal from "./Component/Modal";

import "./styles.css";
export default class App extends Component {
constructor(props) {
super();
this.state = {
show: false
};
}
showModal = e => {
this.setState({
show: true
});
this.setState({
show: !this.state.show
});
};
render() {
return (
<div className="App">
<Modal onClose={this.showModal} show={this.state.show} />
<button
onClick={e => {
this.showModal();
}}
>
Show
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Modal.js

import React from "react";
export default class Modal extends React.Component {
constructor(props) {
super();
this.state = {};
}
onClose = e => {
this.props.show = false;
this.props.onClose && this.props.onClose(e);
};
render() {
if (!this.props.show) {
return null;
}
return (
<div>
{this.props.children} in Modal
<button
onClick={e => {
this.onClose(e);
}}
>
Close
</button>
</div>
);
}
}

我试过像这样按照 App.js 的第一个答案,但它没有用,我想我已经尝试了答案中提到的第二件事,并且这就是为什么我有两个只是测试我知道是错误的东西。

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Modal from "./Component/Modal";

import "./styles.css";
export default class App extends Component {
constructor(props) {
super();
this.state = {
show: false
};
}
showModal = (show) => {
this.setState({
show: show
});
};
render() {
return (
<div className="App">
<Modal onClose={e => this.showModal(false)} show={this.state.show} />
<button
onClick={e => {
this.showModal();
}}
>
Show
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

您的回答将填补此 bits and pieces article 的空白

最佳答案

我做了切换你的显示按钮,如果你想使用关闭按钮关闭这也有效。您可以根据需要随意更改。

App.js

export default class App extends Component {
constructor() {
super();
this.state = {
show: false
};
}
showModal = () => {
this.setState(prev=>({
show: !prev.show
}));
};
render() {
return (
<div className="App">
<Modal onClose={this.showModal} show={this.state.show} />
<button
onClick={e => {
this.showModal();
}}
>
Show
</button>
</div>
);
}
}

模型/index.js

export default class Modal extends React.Component {
render() {
if (!this.props.show) {
return null;
}
return (
<div>
{this.props.children} in Modal
<button
onClick={this.props.onClose}
>
Close
</button>
</div>
);
}
}

关于javascript - 如何在 react 中切换模态并传递子 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59241823/

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