【发布时间】:2020-07-24 19:55:15
【问题描述】:
我的主应用程序包含一个文本、一个文本输入(一个组件)和一个按钮(另一个组件):
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Alert } from 'react-native';
import { Tinput } from './components/Tinput.js';
import { Button } from './components/Button.js';
export default function App() {
return (
<View style={styles.container}>
<Text style={{fontSize:20, padding:20, textAlign:'center'}}>Ingrese un numero del pokémon a buscar!</Text>
<Tinput/>
<Button onPress={()=> ConsultarPokemon(/*this is where i want to insert the value from Tinput */)}>
Ingresar
</Button>
<StatusBar style="auto" />
</View>
);
}
这是我的组件 Tinput,它有文本输入:
import React from 'react';
import { TextInput } from 'react-native';
const Tinput = () => {
const [numero, setNumero] = React.useState('');
return (
<TextInput
style={{ width:'90%', height: 50, borderColor: 'gray', borderWidth: 1, backgroundColor: '#fffff0', textAlign:'center', borderRadius: 20, borderWidth:5, margin:20}}
onChangeText={(value) => setNumero({numero: value})}
value={this.state.numero}
maxLength={20}
/>
);
}
export { Tinput };
我想在我的 onPress 函数上使用文本输入中的值,我尝试这样做但没有成功:
<Button onPress={()=> ConsultarPokemon(Tinput.state.numero)}>
Ingresar
</Button>
另外,我的 Tinput 组件有一个错误:undefined is not an object (evalating '_this.state.numero') 所以我可能也以错误的方式使用状态
【问题讨论】:
-
您不能像这样访问其他组件状态。您只能访问自己的组件状态或访问树中更高组件的状态。所以解决方案是移动使用这两个组件的组件中的状态。
-
所以我必须给应用程序一个数字状态,然后在我的 Tinput 组件上更改应用程序的状态?我将如何访问该状态? app.setNumber({number:value}) ?
标签: javascript android reactjs react-native native