【问题标题】:React Navigation passing function as parameterReact Navigation 传递函数作为参数
【发布时间】:2021-06-21 05:48:09
【问题描述】:

所以我有很多具有类似功能的屏幕,例如:

  1. 忘记密码验证码
  2. 忘记用户ID验证码
  3. 注册验证码

这些屏幕具有相同的布局和功能,只是它们在 ForgotPassword 中具有不同的“下一步”按钮功能,用户将被重定向到登录屏幕,在 ForgotUserID 中,用户将被重定向到显示其用户 ID 的页面。并在注册中将用户重定向到成功页面。 .

所以我在导航器中创建的功能是 handleOkay,当我按下 SomeReusableScreen 中的按钮时,它会给我这个警告

Non-serializable values were found in the navigation state. Check:

forgotUserIDStackScreen > FUinputCASAScreen > params.handleOkay (Function)

This can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. 

我想要实现的是我在堆栈导航器中将函数作为参数传递,这样屏幕只会调用该函数来重定向/使用 redux 做某事,

我不知道我应该忽略这个警告,因为在其他屏幕中它将处理 redux sagas,设置 asyncstorage

【问题讨论】:

标签: react-native react-navigation redux-saga react-navigation-v5


【解决方案1】:

我实现了一个非常简单的例子来明确这个概念。您可以将函数作为道具传递,并且可以使用相同的道具键将其分派到父组件。这样您就可以利用可重用的组件。

//consider this your generic Component
function IButton(props){
  //receive the method as props
  //dispatch the method back to the parent
  return (
    <button onClick={()=>props.handleClick('hello')}>click me </button>
  )
}
const App=()=>{
   function handleOnClick(text){
       alert(text);
   }
  return(
    <div>
       {/*pass the function as Prop*/}
      <IButton handleClick={handleOnClick}/>
    </div>
  )
  
}
  ReactDOM.render( < App / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 您好,感谢您的回复,我已经完成了布局,但我想要实现的是重用具有从 route.params.handleOkay 触发功能的相同按钮的屏幕。目前它正在工作,但由于警告,我不确定我是否应该这样做,我不确定它是否会在未来造成麻烦
【解决方案2】:

所以我找到了做我想做的事的方法。

我没有像这样将屏幕作为组件传递给 Stack.Screen,而是将其作为子组件传递

<Stack.Screen
          initialParams={{progress: 0.2}}
          name={routes.nameofthisroute}
          options={({navigation, route}) => ({
            headerTitle: props => {
              let currentProps = {navigation, route};
              return <NavigationHeaderTwo {...currentProps} />;
            },
            ...otherStyle,
          })}>
          {props => (
            <PickMethodScreen handlePickMethod={handlePickMethod} {...props} />
          )}
        </Stack.Screen>

我从 Stack Navigator 中支持了一些函数和状态,它写在这个docs here

我们还可以创建反应上下文,这样组件就可以在没有大量道具的情况下使用它

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2020-05-29
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多