簡體   English   中英

如何在 onClick 事件反應 js 上從子級渲染其他組件?

[英]How to render other component from children on onClick event react js?

如何在 onClick 事件上從一個組件的 HTML 元素渲染另一個組件?

//ChildComp.jsx

import NextElement from "./NextElement";

const AuxMenu = () => {
  
  const [element, setElement] = useContext(ElementContext);
  
  function changeState(e){
    setElement(e.target.innerText)
  } 
  
  return (
    <div onClick={(e)=>{changeState(e) && <NextElement />}}>Click me</div>
  );
};

export default AuxMenu;


//NextElement.jsx

imr
function NextElement(){
  return <button>Next Button</button>
}

這確實是一個錯誤的代碼,我只是想顯示參考。

查詢:單擊div時, changeState()應該更新state中的元素名稱,然后它應該呈現給NextElement組件並替換/刪除前一個組件。 (類似於 React 路由器的功能,但我的應用程序是單頁應用程序,因此我沒有要定義的路徑或鏈接)

編輯:

這有點像你要找的東西。

如果您有任何問題,請告訴我。

//ChildComp.jsx
import NextElement from "./NextElement";

const AuxMenu = () => {
  
  const [showElement, setShowElement] = useState(false);
  
  function changeState(){
    setShowElement(!showElement)
  } 
  
  return (
    <>
      {!showElement && <div onClick={changeState}>
        Click me
      </div>}
      {showElement && <NextElement />}
    </>
  );
};

export default AuxMenu;


//NextElement.jsx
function NextElement(){
  return <button>Next Button</button>
}

與 React Router 一樣,您需要定義您的路由,或者在本例中為steps 最簡單的方法是為每個步驟創建一個組件,例如FirstStepSecondStep等。

然后創建一個數組。 該數組將包含返回步驟組件的函數。 數組中的順序決定了步驟的順序。

// You'll have to create the components yourself.
import { FirstStep, SecondStep } from './components'; 

// Put them in an array.
const steps = [
  (props) => <FirstStep {...props} />,
  (props) => <SecondStep {...props />,
];

現在在您的主要組件( AuxMenu )中,保留一個索引,以跟蹤步驟中當前的 position,從0開始。

使用此索引 select 來自steps數組的組件並渲染它。

現在,當您想將 go 進行下一步時,您所要做的就是增加數組中的當前 position。 因此currentStep + 1將為您提供下一步。

// The steps array.
import { steps } from './steps';

const AuxMenu = () => {
  const [currentStep, setCurrentStep] = useState(0);

  const hasNextStep = currentStep + 1 < steps.length;
  
  const nextStep = () => {
    if (hasNextStep) {
      setCurrentStep(currentStep => currentStep += 1);
    }
  };

  const StepComponent = steps[currentStep];
  
  return (
    <div>
      <StepComponent someprop={'hello'} />
      {hasNextStep && <button onClick={nextStep}>Next step</button>}
    <div/>
  );
};

如果沒有看到 ElementContext 內部的內容,很難說,但看起來您正在將文本設置為存儲在 element.xml 中。

假設您有 2 個組件 A 和 B:

const A = () => {
  const [element, setElement] = useContext(ElementContext);
  return (
    <p onClick={() => setElement(“B”)}>Hello</p>
  )
}

const B = () => {
  return (
    <p>Goodby</p>
  )
}

還有一些父組件 P :

const P = () => {
  const [element, setElement] = useContext(ElementContext);
  return (
    <>
      {element === ‘A’ ? <A /> : <B />}
    </>
  )
}

如果單擊 A 中的段落標記,則父級將首先呈現 A 組件(假設“A”是 ElementContext 的默認值)和 B。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM