Home > database >  React-native useState
React-native useState

Time:11-27

I'm new and need to use useState but how do I bind the button in a separate component and the Text in another component?

components 1
const Bottom = () => {
  const [counter, setCounter] = useState(0);

  function number() {
    setCounter(counter   1);
  }
  console.log(counter);
components 1
<View style={styles.seperator}>
        <TouchableOpacity style={styles.button} onPress={number}>
          <Text style={styles.buttonText}>Save</Text>
        </TouchableOpacity>
      </View>
components 2
<Text style={styles.number}>{props.counter}</Text>

My full code

import React, {useState, useEffect} from 'react';

import {View, Text, StyleSheet} from 'react-native';

import styles from './Header.styles';
const Header = props => {
  return (
    <View style={styles.container}>
      <View style={styles.headContainer}>
        <Text style={styles.title}>TODO..</Text>
        <Text style={styles.number}>{props.counter}</Text>
      </View>
    </View>
  );
};

export default Header;





import React, {useState} from 'react';

import {
  View,
  Text,
  Stylesheet,
  TouchableOpacity,
  TextInput,
} from 'react-native';
import {Header} from 'react-native/Libraries/NewAppScreen';

import styles from './Bottom.styles';

const Bottom = () => {
  const [counter, setCounter] = useState(0);

  function number() {
    setCounter(counter   1);
  }
  console.log(counter);
  return (
    <View style={styles.bottomContainer}>
      <TextInput
        style={styles.input}
        placeholder="Todo"
        onChangeText={text => setText(text)}></TextInput>

      <View style={styles.seperator}>
        <TouchableOpacity style={styles.button} onPress={number}>
          <Text style={styles.buttonText}>SAVE</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default Bottom;

The code has 2 components, I want the number to increase when I press the button

i uploaded all my code sorry if it's a bad question i'm new

I tried to import props and pages

CodePudding user response:

What i understand is that you try to achieve this

const component1 = ({state1,setState1})=>{return()}
const component2 = ({state2,setState2})=>{return()}

then in your screen

const HomeScreen = () =>{
 const [yourState1,setYourState1]= useState(someValue1);
 const [yourState2,setYourState2]= useState(someValue2);

  return(
    <View>
     <Component1 state1={yourstate1} setState1={yourSetstate1} />
     <Component2 state2={yourstate2} setState1={yourSetstate2} />
    </View>

)
}

Component1 can be your button, Component2 can be your Text Component This way you can manipulate your state.

  • Related