【问题标题】:React native how can parent to pass a function to the childReact Native 父母如何将函数传递给孩子
【发布时间】:2016-12-25 03:39:35
【问题描述】:

在 react native 中,如果想让孩子调用父母的函数,我可以这样做:

在父母中:

<Child myFunc={this.handleChildFunc.bind(this)} />

孩子会这样调用该函数:

onpress=this.props.myFunc();

如何在 Navigator 和 NavigatorIOS 中通过 passProps 实现这一点?

<NavigatorIOS
    initialRoute={{
      component: MyScene,
      title: 'My Initial Scene',
      passProps: { myProp: this.handleChildFunc.bind(this) }  // Not work
      passProps: { myProp: ()=>this.handleChildFunc.bind(this) }  //Not work
    }}
    style={{flex: 1}}
  />

更新

感谢您的回复,但我是新来的本机反应,不太了解如何在 navigatorIOS 中实现以下答案。但是,我尝试了以下方法,孩子可以成功调用父母的函数

在 parent 中,将回调作为 props 传递

passProps: { parentFunc: ()=>this.handleFunc() }

在孩子中

this.props.handleFunc();

【问题讨论】:

    标签: react-native parent-child navigator


    【解决方案1】:

    这段代码对我有用

    return(
        <NavigatorIOS
            initialRoute={{
              component: MyScene,
              title: 'My Initial Scene',
              myProp: (() => { this.handleChildFunc.bind(this) }) // work
            }}
            renderScene={ (route, navigator) =>
              <Child navigator={navigator} {...route.passProps} onFun={ route.myProp } /> 
            }
          />
    )
    

    当调用孩子时

    this.props.onFun()
    

    Check here

    【讨论】:

    • 感谢您的回答。
    【解决方案2】:

    有一个demo,也许有帮助。

    renderScene 函数示例:

    renderScene(route, navigator) {
      let Component = route.component;
      return <Component {...route.params} navigator={navigator} />
    }
    

    新场景推送示例:

    this.props.navigator.push({
      component: Child,
      func: customFunc
    })
    

    然后您可以在子页面(二级页面)中使用this.props.func

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 2018-08-04
    • 2018-06-29
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2021-10-31
    相关资源
    最近更新 更多