反应,当其他组件上的状态相等时更改组件

问题描述 投票:0回答:1

嘿,我有一个小问题,我有一些类似幻灯片放映应用程序的东西,当我们完成第一张幻灯片上的所有幻灯片时,我想将组件更改为另一个组件。

import { useState } from 'react';

const text = [
    "Text1",
    "Text2",
    "Text3",
    "Text4",
    "Text5"
]

export function Intro() {
    let [index, setIndex] = useState(0)

    const handleIndexIncrease = () => {
        if (index == text.length - 1){
            return <Test/>;
        } else {
            setIndex(index + 1)
        }
    }

    return (
        <>
            <div className="mainContainer">
                <h1>{text[index]}</h1>
                <button id='btn' onClick={handleIndexIncrease}>&#129046;</button>
            </div>
        </>
    )
}

function Test() {
        return (
            <>
                <div className="mainContainer">
                    <h1>Component2</h1>
                </div>
            </>
            )
}

我有 5 个文本和一个按钮,可以将其更改为另一个文本,当所有文本完成后,我想渲染 Test() 组件(因此当 index === text.length - 1 时)。我知道

        if (index == text.length - 1){ return <Test/>; }
不会重新渲染任何内容,因此不会显示,但我不知道如何写好

我尝试过状态共享

export function Intro() {
    let [index, setIndex] = useState(0)

    const handleIndexIncrease = () => {
        if (index == text.length - 1){
            return <Test isActive={index == text.length - 1}/>;
        } else {
            setIndex(index + 1)
        }
    }

    return (
        <>
            <div className="mainContainer">
                <h1>{text[index]}</h1>
                <button id='btn' onClick={handleIndexIncrease}>&#129046;</button>
            </div>
        </>
    )
}

function Test({isActive}) {
    if(isActive === 1) {
        return (
            <>
                <div className="mainContainer">
                    <h1>ESA</h1>
                </div>
            </>
            )
        }

}


但它仍然没有重新渲染任何东西

javascript html css reactjs react-hooks
1个回答
0
投票

请像这样更改您的代码:


import { useState } from 'react';

const text = [
  "Text1",
  "Text2",
  "Text3",
  "Text4",
  "Text5"
]

export default function Test3() {
  let [index, setIndex] = useState(0)

  const handleIndexIncrease = () => {
    if (index == text.length ) {
      // console.log('here!')
      //   return <Test/>;
    } else {
      setIndex(index + 1)
    }
  }

  return (
    <>
      <div className="mainContainer">
        <h1>{index == text.length ? <Test /> : text[index]}</h1>
        <button id='btn' onClick={handleIndexIncrease}>&#129046;</button>
      </div>
    </>
  )
}

function Test() {
  return (
    <>
      <div className="mainContainer">
        <h1>Component2</h1>
      </div>
    </>
  )
}

我不确定我是否理解你的目标。 但更改组件即可正常工作。 或者您想在更改完成后隐藏按钮吗?

如果您的答案是肯定的,请使用此代码


<button id='btn' onClick={handleIndexIncrease} hidden = {index == text.length}>&#129046;</button>

© www.soinside.com 2019 - 2024. All rights reserved.