【发布时间】:2021-09-21 23:14:30
【问题描述】:
我正在尝试制作一个可重用的文本输入组件,但我想获取用户键入的值以在 App.js 上对其进行操作
TextInputComponent.js
import React, {useState} from 'react';
import { StyleSheet, View, TextInput } from 'react-native'
const TextInputComponent = (props) => {
const [text, onChangeText] = useState("")
return (
<View>
<TextInput style={styles.container} value={text} onChangeText={onChangeText} placeholder="Enter"/>
</View>
)
}
const styles = StyleSheet.create({
container: {
height: 50,
width: 200,
padding: 10,
margin: 10,
borderWidth: 1,
borderColor: "black",
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default TextInputComponent
App.js
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
import TextInputComponent from './src/components/TextInputComponent';
export default function App() {
return (
<View style={styles.container}>
<View style={{flexDirection: 'row' }}>
<Text>Test</Text>
<TextInputComponent/>
<Button title="A" onPress={()=> console.log(-------> text value from TextInputComponent <-----)}></Button>
</View>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
为了访问在 TextInputComponent.js 上创建的状态值,我需要做什么?
【问题讨论】:
-
你必须去reactjs.org 阅读关于道具的信息。您在 component 参数中调用 props 并且没有使用它们。这不是基本的反应,它是必不可少的反应,如果你不知道怎么做,我建议一些 youtube 教程。
标签: react-native redux react-hooks state react-props