如何从文本输入(组件)到我的主应用程序获取值?

时间:2020-07-24 19:55:15

标签: javascript android reactjs react-native native

我有一个带有文本,文本输入(一个组件)和一个按钮(另一个组件)的主应用程序:

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组件上有一个错误:未定义不是对象(正在评估'_this.state.numero') 所以我也可能以错误的方式使用状态

1 个答案:

答案 0 :(得分:1)

仅当创建了类似组件类之类的类时,才使用this.state.X,这是一个示例:

    class Counter extends React.Component {
      constructor(props) {
        super(props);
        this.initialCount = props.initialCount || 0;
        this.state = {
          count: this.initialCount
        }
      }
increment() {
    this.setState({ count: this.state.count + 1 })
  }
  reset() {
    this.setState({ count: this.initialCount})
  }
  render() {
    const { count } = this.state;
    return (
      <>
        <button onClick={this.increment.bind(this)}>+1</button>
        <button onClick={this.reset.bind(this)}>Reset</button>
        <p>Count: {count}</p>
      </>
    );
  }
}

我建议不要使事情复杂化,而只需在Tinput内处理onPress

    const Tinput = () => {
      const [numero, setNumero] = React.useState('');
    
      return (
    <View>
        <TextInput
          style={{ width:'90%', height: 50, borderColor: 'gray', borderWidth: 1, backgroundColor: '#fffff0', textAlign:'center', borderRadius: 20, borderWidth:5, margin:20}}
          onChangeText={(value) => setNumero(value)}
          value={numero} // no need to use this.state.numero
          maxLength={20}
        />
 <Button onPress={()=> ConsultarPokemon(numero)}> 
        Ingresar 
  </Button> 
 </View>
      );
    }
相关问题