【问题标题】:React Native - Handle parent state from child component (custom component) without add function in parentReact Native - 处理来自子组件(自定义组件)的父状态,而不在父组件中添加功能
【发布时间】:2019-02-24 10:19:53
【问题描述】:

我已经阅读了this answer,但我想稍微改变一下代码的结构,

实际上我想从子组件设置父状态,但我不想在父组件中添加任何功能

实际上预期的结果是这样的:

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state={modalVisible:false}
  }

  render() {
    return (
      <Child modalVisible={this.state.modalVisible} />
      <Button onClick={()=>this.setState({modalVisible:true})/>
    )
  }
}

class Child extends React.Component {

  handler(e) {
    //handle parent moadlVisible state to false again
  }

  render() {
    return
      <Modal
        modalVisible = {this.props.modalVisible}>
        <Button title="Close Modal" onPress={()=>this.handler(e)}/>
      </Modal>
  }
}

所以我想让调用child component 变得容易,而不需要在parent 中添加一些函数来处理child component 本身,即使关闭child componentmodal 也是如此

有没有办法实现我想要的?

【问题讨论】:

    标签: react-native components state


    【解决方案1】:

    如果您根本不希望这两个组件之间有任何连接,那么您可能必须使用全局状态存储,例如 redux。

    文档可以在这里找到:

    https://redux.js.org/introduction

    Redux 在所有组件之间创建一个全局状态而不是局部状态。它确实需要一些配置,但是一旦您将其完全集成,您就可以处理您的场景。此外,随着组件的增长,跟踪状态会更容易。

    为什么我不能只使用事件?

    在这里引用一个问题..

    react.js custom events for communicating with parent nodes

    React 的方式是将回调显式传递给子级 通过道具——。不支持带有冒泡的自定义事件 反应。

    反应式编程抽象是正交的:

    通过观察者模式对交互系统进行编程是 困难且容易出错,但仍然是许多实施标准 生产环境。我们提出了一种逐渐弃用的方法 支持反应式编程抽象的观察者。一些 库层帮助程序员顺利迁移现有代码 回调到更具声明性的编程模型。

    在我看来,一种可怕的做法可能是使用Async Storage

    存储键值,但我不建议这样做。

    【讨论】:

    • 我读过redux,但这意味着我的组件只能用于redux项目对吗?实际上我想使用modal 创建一个custom alert 组件,
    • 我没有完全理解你对redux项目的意思? Redux 创建一个全局存储。您可以将组件连接到全局存储,或者/并且您也可以使用本地状态
    猜你喜欢
    • 2021-03-23
    • 2020-01-05
    • 2020-12-03
    • 2021-12-27
    • 1970-01-01
    • 2021-01-12
    • 2017-12-06
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多