reactjs - 通过不更新状态的道具将功能从父组件传递到子组件来关闭 react-bootstrap 弹出模式
问题描述
我无法this.togglePopup
通过 props 将父函数传递给子组件来更新父反应组件的状态。
我可以通过将父组件传递给子组件来成功打开引导模式(react-bootstrap)this.state.open
,但无法通过this.togglePopup
传递给子组件的函数关闭弹出窗口/更新父组件的状态。
该应用程序是使用create-react-app
.
公共/index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossOrigin="anonymous"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
src/App.js
import React from 'react';
import Parent from './components/Parent';
import './App.css';
function App() {
return (
<div className="App">
<Parent></Parent>
</div>
);
}
export default App;
src/components/Parent.js
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
this.togglePopup = this.togglePopup.bind(this);
}
togglePopup() {
this.setState({
open: !this.props.open
});
}
render() {
return (
<div>
<a onClick={this.togglePopup}>Open Modal</a>
<Child show={this.state.open} parentAction={this.togglePopup}/>
</div>
);
}
}
export default Parent;
src/components/Child.js(弹出模式)
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
show: props.show
};
}
render() {
return (
<>
<Modal show={this.props.show} onHide={this.props.parentAction}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.props.parentAction}>
Close
</Button>
<Button variant="primary" onClick={this.props.parentAction}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
}
export default Child;
当然,我错过了一些简单的事情。
非常感谢。
解决方案
在togglePopup
你使用道具的价值时,总是undefined
. 你应该使用this.state.open
togglePopup() {
this.setState({
open: !this.state.open
});
}
推荐阅读
- osrm - OSRM 是否真的为自行车提供公共 http API?
- c# - 消息工作成功完成后 Azure 服务总线“提供的锁无效”
- c# - 不能将 void 分配给隐式类型的变量
- ruby-on-rails - 与 pow 和子域一起前进
- excel - Excel - 有条件地将行转置为列
- mysql - COUNT() 是否高于表中的总行数?
- apache-kafka - 使用 Kafka Kusto Sink 从 Kafka 解析记录 (PCF)
- python - 使用 tox 为 python 运行测试用例时出现 InvocationError
- node.js - 路由时没有获取文件
- c# - 如何在 5x5 网格 WPF C# 中跨越两个按钮的图像