Home > OS >  am new at react native and try to show hello world text once i press the button the below code could
am new at react native and try to show hello world text once i press the button the below code could

Time:08-01

'''
import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react'

const onPressHndler = () => {
    <View>
      <Text>
        Hello world 
      </Text>
    </View>
     
}
export default () =>{
  return(
    <SafeAreaView>
    <View>
  <Button title='press' onPress={onPressHndler}/>
    </View>
    </SafeAreaView>
  )
}

CodePudding user response:

export default () =>{
  const [isContentVisible , setContentVisible] = useState(false)
  return(
    <SafeAreaView>
    <View>
      <Button title='press' onPress={() => setContentVisible(true)}/>
      { isContentVisible &&
        <View>
          <Text>
            Hello world 
          </Text>
        </View>
      }
    </View>
    </SafeAreaView>
  )
}

CodePudding user response:

    export default () =>{
    const [showContent , setShowContent] = useState(false)

    onPressHandler = ()=>{
        setShowContent(true)
    }
    return(
        <SafeAreaView>
        <View>
        <Button title='press' onPress={onPressHandler}/>
        { showContent &&
            <View>
            <Text>
                Hello world 
            </Text>
            </View>
        }
        </View>
        </SafeAreaView>
    )
    }

your function must define the action you expect your code to do not the outcome you expect to see, while the condition in your JSX will make sure that the content follows this logic.

You can even alter the same state false/true

    export default () =>{
    const [showContent , setShowContent] = useState(false)

    onPressHandler = ()=>{
        setShowContent(!showContent)
    }
    return(
        <SafeAreaView>
        <View>
        <Button title='press' onPress={onPressHandler}/>
        { showContent &&
            <View>
            <Text>
                Hello world 
            </Text>
            </View>
        }
        </View>
        </SafeAreaView>
    )
    }

Now a press on the button will show content, another will hide it.

  • Related