使用高阶组件有条件地渲染列表 [英] Conditionally render list with Higher Order Component
问题描述
我的应用程序具有功能切换功能,该功能告诉我的UI是否应渲染一个UI.我想创建一个高阶组件来有条件地呈现这些类型的组件.在一种情况下,我试图有条件地呈现一个列表,但是我遇到了这个错误:
My app has a feature toggle functionality that tells my UI whether or not a piece of UI should be rendered. I would like to create a Higher Order Component to conditionally render these types of components. In one scenario, I'm trying to conditionally render a list, but I'm running into this error:
ConditionalRender(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
这很有意义,因为我只是尝试渲染此组件的子代.这是到目前为止我得到的:
This makes sense since I just am trying to render the children of this component. Here's what I've got so far:
https://jsfiddle.net/fmpeyton/cykmyabL/
var settings = { showHello: true, showGoodbye: false};
function ConditionalRender (props) {
var output = null;
if(props.shouldRender) output = props.children;
console.log(output);
// return (<li>{output}</li>); // This works, but isn't desired html structure
return ({output});
}
function App (props) {
return (
<ul>
<ConditionalRender shouldRender={props.settings.showHello}>
<li>Hello!</li>
</ConditionalRender>
<ConditionalRender shouldRender={props.settings.showGoodbye}>
<li>Goodbye...</li>
</ConditionalRender>
</ul>
);
}
ReactDOM.render(
<App settings={settings} />,
document.getElementById('container')
);
如果我能帮忙的话,我只想在不增加任何逻辑的情况下渲染子代,此HOC还将处理更复杂的子代.像这样:
If I can help it, I would just like to render the children without any additional logic.This HOC would also handle more complex children down the line. Something like this:
<ConditionalRender shouldRender={props.settings.showHello}>
<div>
<p> blah blah blah</p>
<table>
<!-- ... -->
</table>
</div>
</ConditionalRender>
有什么想法吗?
推荐答案
尝试一下:
function App(props) {
return (
<ul>
{props.settings.showHello && <li>Hello!</li>}
{props.settings.showGoodbye && <li>Goodbye...</li>}
</ul>
);
}
PS .由于此行,您的代码无效:
P.S. Your code doesn't work because of this line:
return ({output});
假设您拥有es2015支持,它将被视为对象属性速记.因此,它与:
Assuming you have es2015 support, it would be treated as object property shorthand. So it's the same as:
return {output: output};
这不是React期望从render
方法获得的结果.
which is not what React expects to get from the render
method.
您可以尝试以下方法:
function ConditionalRender(props) {
if (props.shouldRender) {
// Make sure we have only a single child
return React.Children.only(props.children);
} else {
return null;
}
}
但这不是最简单的方法.查看更多此处.
But this is not the simplest way. See more here.
P.P.S..ConditionalRender组件不是所谓的高阶组件.根据 docs ,HOC是函数需要一个组件并返回一个新组件.
P.P.S. Your ConditionalRender component is not what is called Higher-Order Component. According to the docs, HOC is a function that takes a component and returns a new component.
这篇关于使用高阶组件有条件地渲染列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!