简体   繁体   English

从 React-Native 中的不同屏幕组件在 App 中调用 function

[英]Calling a function in App from a different Screen component in React-Native

I'm developing an app for tuning pianos in react-native.我正在开发一个用于在 react-native 中调整钢琴的应用程序。 I have an App.js and some screens implemented with react-navigation.我有一个 App.js 和一些用 react-navigation 实现的屏幕。 The question is, how I can call a function in App.js from another Screen component in react-native?问题是,如何从 react-native 中的另一个屏幕组件调用 App.js 中的 function? I'm missing something of react-native, I searched on the web but I can't find something really useful.我缺少 react-native 的一些东西,我在 web 上进行了搜索,但找不到真正有用的东西。

The App.js code: App.js 代码:

 export default class App extends Component {... testFunction = () => {... } render() { return ( <NavigationContainer> <Provider store={store}> <Tab.Navigator activeColor="#000" barStyle={{ backgroundColor: "white" }}> <Tab.Screen name="Tuner" component={TunerScreen} options={{ tabBarLabel: "Home", tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="home" color="black" size={26} /> ), }} /> <Tab.Screen name="Beats" component={BeatsScreen} options={{ tabBarLabel: "Beats", tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="blur-radial" color="black" size={26} /> ), }} /> <Tab.Screen name="Inharmonicity" component={InharmonicityScreen} options={{ tabBarLabel: "Parameters", tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="cog" color="black" size={26} /> ), }} /> </Tab.Navigator> </Provider> </NavigationContainer> ); } }

And the Screen component code:以及 Screen 组件代码:

 class TunerScreen extends Component { render() { return ( <View style={style.body}>... <Button style={style.btn} onPress={() => testFunction()} //Here i want to call the function title="Start" color="#841584" accessibilityLabel="Start" /> </View> ); } }

Thanks for the answers!感谢您的回答!

You should be able to pass the props like this你应该能够像这样传递道具

<Tab.Screen
              name="Inharmonicity"
              component={(props) => <InharmonicityScreen testFunction={this.testFunction} {...props} />}
              options={{
                tabBarLabel: "Parameters",
                tabBarIcon: ({ color }) => (
                  <MaterialCommunityIcons name="cog" color="black" size={26} />
                ),
              }}
            />

Remember to use this.testFunction = this.testFunction.bind(this)记得使用this.testFunction = this.testFunction.bind(this)

Then in desire Screen you can use props.testFunction() after declaring super(props) in constructor.然后在愿望屏幕中,您可以在构造函数中声明super(props)后使用props.testFunction()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM