我无法通过props将父函数this.togglePopup
传递给子组件来更新父反应组件的状态。
我可以通过将父级的this.state.open
传递给孩子来成功打开引导程序模式(react-bootstrap),但无法通过传递的this.togglePopup
函数来关闭弹出窗口/更新父级组件的状态给孩子。
使用create-react-app
引导了应用程序。
public / 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;
当然,我错过了一些简单的事情。
非常感谢。
答案 0 :(得分:1)
在togglePopup
中,您使用道具的价值,即始终为undefined
。您应该使用this.state.open
togglePopup() {
this.setState({
open: !this.state.open
});
}
答案 1 :(得分:0)
实际上,对于钩子,您只需将setModal(true)作为道具传递即可
const [modalShow, setModalShow] = useState(false);
<AddUserModal
show={modalShow}
onHide={modalClose}
setModalShow={setModalShow}
></AddUserModal>
{/* in the AddUserModal */}
{/* get props */} { setModalShow } = props;
{/* persist it to the next Component as a function */}
<SignUp setModalShow={setModalShow} />
{/* consume it in SignUp as the function it is maybe after a network call */}
setModalShow(false)
总而言之,您可以将函数作为道具传递