Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

reactjs - How to toggle multiple views with buttons

I'm struggling with this piece of code for a while, I have 5 buttons on the screen and want them to show some view when clicked, but also hide the previous view (showing only ONE view at the time)

I currently have this:

      const [state1, setState1] = useState(false)
      const [state2, setState2] = useState(false)
    //...
    return()
    //Button
    <View/>
    <TouchableOpacity
    onPress={() => setState1(!state1)}
    style={styles.style1}
    >
    <Image
    style={styles.imageButton}
    source={require('./image1')}
    />
    </TouchableOpacity>
    <TouchableOpacity
    onPress={() => setState2(!state2)}
    style={styles.style2}
    >
    <Image
    style={styles.imageButton}
    source={require('./Image2')}
    />
    </TouchableOpacity>
    </View>
//Views
{state1 === true ? (
<View>...</View> ) : null
{state2 === true ? (
<View>...</View> ) : null

This code is working but when I click on button2, the view of button1 is still visible (above in this case) how could I work that out?

question from:https://stackoverflow.com/questions/65945395/how-to-toggle-multiple-views-with-buttons

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const[state, setButtonStatus]=useState("1")
{return<>
  <View>
        {state == "1" ? (
          <Text>First View</Text>
        ) : state == "2" ? (
          <Text>2nd View</Text>
        ) : state == "3" ? (
          <Text>3rd View</Text>
        ) : (
          <Text>4th View.</Text>
        )}
      </View>
</>
}

You can do like that change value of state on clikck and show view accordingly


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...