问题描述
我有一个带有两个子代的组件,其中一个是一个按钮,用于切换状态(modalVisible),该状态决定另一个子代(模态)是否可见。
我无法在父母和模态孩子之间共享开/关状态。我尝试将状态保留在父级中,然后将其作为道具传递给孩子,但并不是每次父级状态更改时都重新渲染孩子。
<CommentsModal visible={modalVisible} />
内部CommentsModal.js ...
import Modal from 'react-native-modal';
...
const CommentsModal = ({visible}) => {
const [modalVisible,setModalVisible] = useState(visible);
...
return <Modal visible={modalVisible} />
}
我考虑过将状态完全保留在父级中,而无需将其传递到CommentsModal中,就像这样:
function renderModal() {
if (modalVisible) {
return <CommentsModal visible={true} />
} else {
return <View />
}
}
但是我意识到,CommentsModal内部必须有一个状态,因为我需要一个“ X”按钮来关闭模式。
我不确定执行此操作的最佳方法是...我可以执行redux,但是由于这些模态有动态的数量,我不希望我的商店那么复杂。我能想到的唯一方法是将所有模式代码都移到父组件中,然后它们可以轻松共享状态,但是对我来说似乎很肮脏。有人有解决方案吗?
解决方法
您的直觉将状态保留在父组件中是正确的。要实现x按钮,您所需要做的就是将onClose
道具传递给模态,该道具将是一个将modalVisible
设置为false的函数。所以你最终会得到这样的东西:
// parent component
const ParentComponent = () => {
const [modalVisible,setModalVisible] = useState(false);
const openModal = () => setModalVisible(true);
const closeModal = () => setModalVisible(false);
return (
<div>
<CommentsModal visible={modalVisible} onClose={closeModal} />
<button onClick={openModal}>open the modal</button>
<p>other children here...</p>
</div>
)
}
// CommentsModal
const CommentsModal = (props) => (
<Modal visible={props.visible}>
<button onClick={props.onClose}>X</button>
<p>more modal content here...</p>
</Modal>
)