【问题标题】:How to pass a component's function to a component inside of navigationoptions如何将组件的功能传递给导航选项内的组件
【发布时间】:2018-12-02 09:31:43
【问题描述】:

所以我这几天一直在处理这个问题,并且一直在谷歌上搜索并尝试实施解决方案。大多数解决方案建议使用 this.props.navigation.setParams({function: this.function.bind(this))componentDidMount 内,然后在 navigationOptions 中执行类似的操作 ->

static navigationOptions = {
header:  ({navigation})  => 
   <Button onPress = { () => navigation.state.params.function}/> }

这适用于带有 onPress 的按钮,但当它只是自定义组件的“道具”时,此方法似乎不起作用。

这是我的代码

static navigationOptions = {
header:  ({navigation})  => 
   <CustomCar refreshCar = {navigation.state.params.refreshCarSearch}
   />

transitionConfig: () => ({
  transitionSpec: {
    duration: 0,
    timing: Animated.timing,
    easing: Easing.step0,
  },
}),
};

constructor(props) {
    super(props)
    this.state =  {
      Car: ' '
    }
    this.refreshCarSearch = this.refreshCarSearch.bind(this);
}

componentDidMount() {
this.props.navigation.setParams({ refreshCarSearch: this.refreshCarSearch });
               }

refreshCarSearch(e){
    this.setState({
        Car: e
        });
                }

我总是得到 navigation.state.params.refreshCarSearch 未定义。我已经尝试了很多这种方法的变体,但无济于事。此方法仅在我用带有 onPress 的按钮替换组件时才有效,但我需要传递此函数。基本上,我需要让我的 CustomCar 组件(它必须位于屏幕顶部,所以在 navigationOptions 中)将一个值传回这个组件,这样才能进行 refreshCarSearch。我读过如何做到这一点的唯一方法是使用 Redux 或父组件将 refreshCarSearch 函数传递给“子”组件的这种情况。 navigationOptions 中存在的组件使它变得更加困难,这可能吗?

【问题讨论】:

  • 您可以尝试将函数作为 screenProps 传递给组件,以便您可以直接在 navigationOptions 中访问 screenProps。
  • @AshwinMothilal 你能再解释一下吗?我不确定语法。我的堆栈导航器位于不同的页面上。你的意思是把它作为道具传递给屏幕组件吗?

标签: react-native react-navigation


【解决方案1】:

如果您希望此客户 Car 组件位于屏幕顶部,则应在渲染函数的顶部调用此组件,然后您将获得 refreshCarSarch this.props.navigation.state.params.refreshCarSearch 例如:

render(){
 return (
   <CustomCar refreshCar = {()=>this.props.navigation.state.params.refreshCarSearch()}
   />
)
}

【讨论】:

  • 我希望它位于导航栏内。否则它就在下面。
【解决方案2】:

考虑一个父组件,您将在道具上发送一个名为 refreshCarSearch 的函数,这在您的情况下不起作用。

<ParentComponent refreshCarSearch={this.refreshCarSearch}/>

所以,你必须像这样发送 refreshCarSearch

<ParentComponent screenProps={{refreshCarSearch:this.refreshCarSearch}}/>

在您的子组件的 navigationOptions 中,您可以像这样访问它

static navigationOptions = ({navigation, screenProps}) {
header:  ()  => 
   <Button onPress = { () => screenProps && screenProps.refreshCarSearch}/> 
}

这里要添加的另一件事是我不确定标题上的参数是否返回导航对象,但上面的参数返回导航和 screenProps 对象(navigationOptions 静态方法参数)。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2021-06-18
    • 1970-01-01
    • 2019-12-13
    • 2019-08-20
    • 2020-06-11
    • 2020-09-05
    • 2020-05-27
    • 2021-04-29
    相关资源
    最近更新 更多