簡體   English   中英

從功能組件內部渲染功能組件

[英]Rendering functional component from inside a functional component

所以我有一個功能組件,它是一個工具欄。 它的父級是一個文本編輯器。 工具欄有許多子組件,它們是按鈕。 單擊其中一個按鈕時,我希望出現一個模式。 useModal的邏輯。 但是FormatToolbarModal沒有出現。

我讀過一個組件的所有渲染都必須由頂級自定義組件完成? 但我不確定 go 從那里到哪里。 我希望此模式可重復使用,因為工具欄中的其他選項將使用它。

索引.jsx

ReactDOM.render(routes, document.getElementById("app"));

應用程序.jsx

const App = () => {
  return (
    <TextEditor/>
  )
}

文本編輯器.jsx

const TextEditor = () => {
  return(
    <FormatToolbar>
      <FormatToolbarBlock format="link" icon={link2} />
      <FormatToolbarBlock format="image" icon={image} />
    </FormatToolbar>
    ... Editor stuff
  )
}


const FormatToolbarBlock = ({ format, icon }) => {
  const editor = useSlate();
  const {isShowing, toggle} = useModal();

  return (
    <FormatButton
      onMouseDown={e => {
        if(format === 'link'){
          toggle(e);
          <FormatToolbarModal       <---- here is my issue
            isShowing={isShowing}  
            hide={toggle}
          />
          } else if {
          ...
          }
      }}
    />
  )
}

使用Modal.jsx

const useModal = () => {
  const [isShowing, setIsShowing] = useState(false);

  function toggle() {
    setIsShowing(!isShowing);
  }

  return {
    isShowing,
    toggle,
  }
};

export default useModal;

格式工具欄Modal.jsx

const FormatToolbarModal = ({ isShowing, hide }) => isShowing ? ReactDOM.createPortal(
  <React.Fragment>
    <p>I am a modal</p>
  </React.Fragment>, document.body 
): null;

export default FormatToolbarModal;

希望從此,您可以更清楚地看到我的問題。 我是 React 和 hooks 的新手,所以任何建議都值得贊賞。

謝謝!

您正在調用 function,但沒有將生成的 JSX 元素傳遞給將呈現它們的任何東西。 想想你在頂級組件中使用的引導操作,你將結果傳遞給ReactDOM.render或類似的。 這就是把它放在頁面上的原因。 您需要對調用模態 function 的結果執行相同的操作。

你有幾個選擇:

  1. 您可以通過設置一個 function 設置的標志,然后在另一個組件中有條件地呈現模式來做到這一點。

  2. 您可以將其渲染為(在?)一個門戶

反應 101。

  1. React 命名約定:組件名稱應遵循 pascal-case。

    例如:從你的代碼 showModal 應該是 ShowModal。

您的代碼也不足以理解結構(這些組件的呈現方式和位置)。 我要說的是還有很多其他可能的方法可以使 go 南下,但僅此一項就可能導致此錯誤。

好吧,正如我懷疑和 TJ Crowder 提到的那樣。 我的FormatButton不知道如何呈現這樣的組件。 我像這樣移動了組件,並將其包裝在一個片段中。 現在一切正常。

對於任何有同樣問題的人。 查看反應門戶。 此外,此鏈接有幫助: https://levelup.gitconnected.com/create-a-modal-with-react-hooks-357c8aae7c3f

文本編輯器.jsx

const FormatToolbarBlock = ({ format, icon }) => {
  const editor = useSlate();
  const {isShowing, toggle} = useModal();

  return (
    <>
    <FormatButton
      onMouseDown={e => {
        if(format === 'link'){
          toggle(e);
          } else if {
          ...
          }
      }}
    />
    <FormatToolbarModal
      isShowing={isShowing}  
      hide={toggle}
    />
    </>
  )
}

暫無
暫無

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

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