使用高阶组件有条件地渲染列表

时间:2017-02-07 02:02:44

标签: reactjs react-jsx jsx

我的应用程序有一个功能切换功能,告诉我的UI是否应该呈现一个UI。我想创建一个高阶组件来有条件地渲染这些类型的组件。在一个场景中,我试图有条件地呈现一个列表,但我遇到了这个错误:

ConditionalRender(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

这是有道理的,因为我正在尝试渲染此组件的子项。这是我到目前为止所得到的:

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也会处理更复杂的孩子。像这样:

<ConditionalRender shouldRender={props.settings.showHello}>
<div>
<p> blah blah blah</p>
<table>
<!-- ... -->
</table>
</div>
</ConditionalRender>

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

试试这个:

function App(props) {
  return (
    <ul>        
      {props.settings.showHello && <li>Hello!</li>}
      {props.settings.showGoodbye && <li>Goodbye...</li>}
    </ul>
  );
}

P.S。由于这一行,您的代码无法运作:

return ({output});

假设您有es2015支持,它将被视为object property shorthand。所以它与:

相同
return {output: output};

这不是React期望从render方法得到的。

你可以试试这个:

function ConditionalRender(props) {
  if (props.shouldRender) {
    // Make sure we have only a single child
    return React.Children.only(props.children);
  } else {
    return null;
  }
}

但这不是最简单的方法。查看更多here

P.P.S。您的ConditionalRender组件不是所谓的高阶组件。根据{{​​3}},HOC是一个函数,它接受一个组件并返回一个新组件

相关问题