簡體   English   中英

反應通過道具的功能組件

[英]React functional components passing props

我有以下組件-myMenu從其父級獲取道具-更改后會正確更新,但是在MyMenuItem組件中它未獲取更新值,它始終像默認值一樣為false? 這是為什么? 我需要像參數一樣傳遞isblack嗎?

const myMenu = ({
      isblack = false,
      data = [],
      type = 'desktop',
    }) => {
      const ConatinerComponent = type === 'desktop' ? Fragment : Somethingelse;
      const containerProps = {
        abc: true,
        def: true,
      };

      const smallComponent = type === 'desktop' ? MyMenuItem : SomeotherFuncComponent;

      return (
        <MyMenuContext.Provider value={{ type }}>
          <ConatinerComponent {...containerProps}>
            {data.map(smallComponent)}
          </ConatinerComponent>
        </MyMenuContext.Provider>
      );
    };

    myMenu.propTypes = {
      isblack: PropTypes.bool,
      data: PropTypes.array,
      type: PropTypes.string,
    };

    export default myMenu;

在同一文件中,我有:

    const MyMenuItem = ({
      abc = '',
      def = '',
      data_nested = [],
      isblack = false,
    }) => {

      console.log('is', isblack); ---- this is always false the default value.???

      .....
      );
    };

    MyMenuItem.propTypes = {
      abc: PropTypes.string,
      isblack: PropTypes.bool,
      def: PropTypes.string,
      nested_data: PropTypes.array,
    };

您擁有它-它需要成為一個論點。 MyMenuItem實際上需要接收isblack道具和您想要傳遞的任何其他道具。因此,在這一行上const smallComponent = type === 'desktop' ? MyMenuItem : SomeotherFuncComponent; const smallComponent = type === 'desktop' ? MyMenuItem : SomeotherFuncComponent; 將其更改為const smallComponent = type === 'desktop' ? <MyMenuItem isblack={isblack}/> : <SomeotherFuncComponent/>; const smallComponent = type === 'desktop' ? <MyMenuItem isblack={isblack}/> : <SomeotherFuncComponent/>;

暫無
暫無

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

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