【问题标题】:React native pass function through props通过 props 反应原生 pass 函数
【发布时间】:2021-04-07 04:45:48
【问题描述】:

我是原生反应新手,我在将函数从父类传递给子类时遇到了一些问题

//Child class
const AppDrawer = ({update_recent}) => {
     update_recent("Notification");
}

//Parent class
const App: () => React$Node = () => {    
    const [recent, setRecent] = useState("Home");

    useLayoutEffect(() => {
       SplashScreen.hide();
    });

    return (
       <NavigationContainer>
          <Stack.Navigator screenOptions={{
            headerShown: false
          }}>
        <Stack.Screen name="Application" component={AppDrawer} update_recent={setRecent}/> //Pass in set recent function to child class.
        <Stack.Screen name="Notifications" component={Notifications} recent_page={recent}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

我将 setRecent 传递给 AppDrawer,以便 AppDrawer 类能够编辑 recent 变量。请让我知道我应该怎么做。

【问题讨论】:

  • 您可以提供更多信息
  • 你使用 javascript 或 typescript 吗?
  • 如果你想从主根导航向你的组​​件传递一个函数。你应该传递一个 prop initialParams 所以它应该是这样的:initialParams={{ update_recent: setRecent }} 你可以从应用程序的导航状态中获取这个功能,例如
  • 这是在我的 App.js 文件中的 JS 中。
  • 这能回答你的问题吗? How to remove warning in React native

标签: reactjs react-native react-native-android react-props


【解决方案1】:

你可以试试

  <Stack.Screen name="Application" component={()=><AppDrawer update_recent={setRecent}/>}/> //Pass in set recent function to child class.

在组件中,而不是直接传递 AppDrawer,您可以传递一个箭头函数,该函数返回 AppDrawer 组件,同时将 setRecent 作为 prop update_recent 传递。


 更新

对屏幕使用渲染回调而不是指定组件属性:

  <Stack.Screen name="Application" component={(props)=><AppDrawer {..props} update_recent={setRecent}/>}/> //Pass in set recent function to child class.

https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props

【讨论】:

  • 非常感谢!它有效,但我收到警告。我在帖子中附上了一张图片,显示了我收到的警告。你能帮我摆脱这个警告吗?谢谢!
  • @KevinWu 使用屏幕渲染回调而不是指定组件属性:``` }/> //将设置最近的函数传递给子类。 ```javascript 见reactnavigation.org/docs/hello-react-navigation/…
猜你喜欢
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2019-05-16
  • 2017-09-24
  • 2020-12-21
  • 2018-02-27
相关资源
最近更新 更多