javascript - react 父/子状态变化设计问题

标签 javascript reactjs react-native parent-child react-native-modal

我有一个带有两个子组件的组件,其中一个是一个按钮,用于切换状态 (modalVisible),决定另一个子组件(模态)是否可见。

我在父级和模态子级之间共享开/关状态时遇到问题。我尝试将状态保留在父级中,然后将其作为 Prop 传递给子级,但每次父级状态更改时它都不会重新渲染子级。

<CommentsModal visible={modalVisible} />

内部评论Modal.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>
)

关于javascript - react 父/子状态变化设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64307969/

相关文章:

android - react native : children view cannot go beyond parent view on Android but it is working on iOS

react-native - react native : How to deteck iPhones with Notch?

javascript - 惊人的 CSS Div 滚动效果,无法解释,提供链接。这是一个网页设计问题,如何获得这样的效果?

javascript - 类外的类变量

javascript - 如何更新这个已弃用的 React.PropTypes 代码

javascript - 如何在 react-google-maps/api 库中使用 containsLocation

react-native - 应用程序发布崩溃 t 不是一个函数

javascript - return 如何处理 javascript 中的多个变量?

javascript - Bootstrap 选项卡 : Next & Previous Buttons for Forms

reactjs - React 将两个函数作为回调传递给 this.setState