![](/img/trans.png)
[英]React - passing props up components tree through functional components
[英]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.