Reactjs 关闭react bootstrap弹出模式,通过props not updating state将功能从父组件传递到子组件
我无法通过将父函数this.togglePopup通过props传递给子组件来更新父react组件的状态 通过将父级的this.state.open传递给子级,我可以成功打开引导模式react引导,但无法通过传递给子级的this.togglePopup函数关闭弹出窗口/更新父级组件的状态 应用程序是使用create-react-app引导的 public/index.html src/App.js src/components/Parent.js src/components/Child.js弹出模式 当然,我错过了一些简单的东西 非常感谢。在togglePopup中,您使用的是道具的值,它总是未定义的。您应该使用此.state.openReactjs 关闭react bootstrap弹出模式,通过props not updating state将功能从父组件传递到子组件,reactjs,react-bootstrap,Reactjs,React Bootstrap,我无法通过将父函数this.togglePopup通过props传递给子组件来更新父react组件的状态 通过将父级的this.state.open传递给子级,我可以成功打开引导模式react引导,但无法通过传递给子级的this.togglePopup函数关闭弹出窗口/更新父级组件的状态 应用程序是使用create-react-app引导的 public/index.html src/App.js src/components/Parent.js src/components/Child.js弹
实际上,对于钩子,你可以像这样通过setModaltrue作为道具
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)
总之,您可以将函数作为道具传递
import React from 'react';
import Parent from './components/Parent';
import './App.css';
function App() {
return (
<div className="App">
<Parent></Parent>
</div>
);
}
export default App;
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;
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() {
this.setState({
open: !this.state.open
});
}
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)