0

I have a React Native component where I want the TextInput in the child to update the state in the parent component. Here is a Snack and here is the code:

import {Component} from 'react';
import { View, StyleSheet, TextInput } from 'react-native';
import Constants from 'expo-constants';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ''
    }
  }
  setParentState = (text) => {
    this.setState({text})
  }
  render() {

    const TabBar = ({text, setParentState}) => {
      return (
        <TextInput
          style={{borderWidth: 1}}
          onChangeText={(searchText) => {
            setParentState(searchText)
          }}
          value={text}
        />
      )
    }

    return (
      <View style={styles.container}>
        <TabBar text={this.state.text} setParentState={this.setParentState.bind(this)}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

export default App;

When I type a character, the TextInput loses focus. How can I fix this?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • 1
    Does this answer your question? [https://stackoverflow.com/q/76065979/20002061](https://stackoverflow.com/q/76065979/20002061) – kiuQ Jun 15 '23 at 01:44

0 Answers0