[英]How to change useState in functional component (child) from class component (parent)
In my parent class I have the following在我的父类中,我有以下内容
<div>
<button onClick(OPEN MODAL)>Open Modal<button/>
<ModalReply /> // default to be closed at first
</div>
ModalReply is the functional component ModalReply 是功能组件
function ModalReply(props) {
const [modalIsOpen, setModalIsOpen] = useState(false)
<div>
<Modal
isOpen={modalIsOpen}
onRequestClose={() => setModalIsOpen(false)}
>
<h1>Test</h1>
</Modal>
</div>
From my parent class I want to access the modal state component and set the useState --> setModalIsOpen to true从我的父类中,我想访问模态状态组件并将 useState --> setModalIsOpen 设置为 true
set the modalState in the parent and pass them as a props of the child component.在父组件中设置 modalState 并将它们作为子组件的道具传递。
in parent在父母
const [modalIsOpen, setModalIsOpen] = useState(false)
const toggleModal = (val) => setModalIsOpen(val)
...
<ModalReply modalisOpen={modalIsOpen} toggleModal={toggleModal}/>
in child在孩子
function ModalReply(props) {
<div>
<Modal
isOpen={props.modalIsOpen}
onRequestClose={() => props.toggleModal(false)}
>
<h1>Test</h1>
</Modal>
</div>
Move the state to the parent, make your ModalReply stateless.将状态移动到父级,使您的 ModalReply 无状态。
const ModalReply = ({ isOpen, onClose }) => (
<div>
<Modal isOpen={isOpen} onRequestClose={onClose}>
<h1>Test</h1>
</Modal>
</div>
);
export default function App() {
const [isOpen, setIsOpen] = useState(false);
const toggle = setIsOpen((oldIsOpen) => !oldIsOpen);
return (
<div className="App">
<button onClick={toggle}>Open Modal</button>
<ModalReply isOpen={isOpen} onClose={toggle} />
</div>
);
}
React data flow is unidirectional, parents can't directly modify the state of child components. React 数据流是单向的,父组件不能直接修改子组件的状态。 To achieve what you want, you need to either:要实现您想要的,您需要:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.