【发布时间】:2021-05-17 11:19:36
【问题描述】:
我没有使用类,我想学习如何手动操作。我正在处理登录屏幕。
https://snack.expo.io/@ericsia/call-function-from-child-component
如果您想向我展示您的代码,您需要保存并分享链接。所以我想要一个显示文本框的功能组件(假设ChildComponent作为函数名称,所以export ChildComponent)。
所以在 Parent/Screen1 我有类似的东西吗?
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import ChildComponent from './components/ChildComponent';
export default function App() {
function checkSuccess()
{
// call helloWorld from here
}
return (
<View style={styles.container}>
<ChildComponent />
<TouchableOpacity style={styles.button}
onPress={ checkSuccess } >
<Text>helloWorld ChildComponent</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10
},
});
所以如果结果是无效的,我想显示一个小的红色错误消息。
something like this
我的方法是,如果我可以从ChildComponent 调用一个函数,那么我仍然可以解决它。
我用谷歌搜索了它,提供的大部分解决方案都是针对课堂的。
我试过useEffectReact.createRefuseImperativeHandle,但没有成功。
首先,我只是想打电话给helloWorld()
import * as React from 'react';
import { TextInput , View, StyleSheet, Image } from 'react-native';
export default function ChildComponent() {
function helloWorld()
{
alert("Hello World");
}
return (<TextInput placeholder="Try to call helloWorld from App.js"/>);
}
另一个问题,如果我的 ChildComponent 中有一个文本框,我如何从父级检索文本/值?
【问题讨论】:
-
这真的很痛苦。你最好在父级
App中声明helloWorld并将其作为道具传递给ChildComponent。我在这里的回答解释了如何以艰难的方式做到这一点:stackoverflow.com/a/64491870/10431574
标签: reactjs typescript react-native