簡體   English   中英

React HOC 功能組件:如何讓任何孩子都有 Parent 的 state 和邏輯

[英]React HOC functional component: How to make any children have Parent's state and logic

我正在嘗試創建一個 React function Hover 組件( 鏈接到沙箱),它將提供其任何{children} hover 行為,即其內部掛鈎和方法:

function WithHover({ children }) {
  const [hover, setIsHover] = React.useState(null);
  const [hoverText, setHoverText] = React.useState("");
  const mouseOver = () => setIsHover((hover) => true);
  const mouseOut = () => setIsHover((hover) => false);

  const childrenWithExtraProp = React.Children.map(children, (child) => {
    return React.cloneElement(child, {
      hover,
      setIsHover,
      hoverText,
      setHoverText
    });
  });

  return (
    <>
      <div
        style={{
          width: "20%",
          height: "20",
          display: "block",
          marginBottom: "5%",
          backGroundColor: "pink"
        }}
      >
        <p>{hoverText}</p>
      </div>

      <main onMouseOver={mouseOver} onMouseOut={mouseOut}>
        {childrenWithExtraProp}
      </main>
    </>
  );
}

export default function App() {

  function Button({ children }) {
    return <button>{children}</button>;
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <WithHover />
      <Button hover={true}>foo</Button>
      <WithHover />
    </div>
  );
}

但是,當我通過控制台檢查<Button/>以查看道具是否存在時,我得到了一個空數組?

function Button(props) { console.log('props', props); // 零道具返回 {props.children}; }

我錯過了什么?

關閉標簽<WithHover/> ,您實際上並沒有使用children道具(它總是無效)。

相反,請嘗試:

<WithHover>
  <Button>foo</Button>
</WithHover>

編輯浪漫-艾倫-fl31f

您以錯誤的方式關閉WithHover標記,並看到錯誤也顯示在屏幕上。 它通過指出導致它失敗的錯誤,清楚地向您展示了解決此問題的方法。 正如丹尼斯瓦什在他的回答中提到的那樣,標簽應該像這樣關閉:

<WithHover>
  <Button>foo</Button>
</WithHover>

暫無
暫無

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

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