最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create Auxiliary (Higher Order Component) in preact? - Stack Overflow

programmeradmin1浏览0评论

I am trying to build an application using preact and I have created a simple ponent known as LayoutComponent.

In Layout ponent I have used Auxilary ponent as shown below:

import { h } from 'preact';
import Aux from '../../hoc/Aux';
const Layout = (props) => (
    <Aux>
        <div>
        Toolbar, Sidebar, Backdrop
        </div>
        <div>
            { props.children }
        </div>
    </Aux>
);
export default Layout;

And below mentioned is my Auxilary ponent code:

const Aux = ( props ) => props.children;
export default Aux;

When I am invoking LayoutComponent from my App.js render() method, the JSX content inside tag is not getting displayed.

If I replace the tag with tag then it is working fine, but I don't need that extra div in my DOM structure.

The DOM is shown something like this in chrome if I use Aux tag.

Please Help.

I am trying to build an application using preact and I have created a simple ponent known as LayoutComponent.

In Layout ponent I have used Auxilary ponent as shown below:

import { h } from 'preact';
import Aux from '../../hoc/Aux';
const Layout = (props) => (
    <Aux>
        <div>
        Toolbar, Sidebar, Backdrop
        </div>
        <div>
            { props.children }
        </div>
    </Aux>
);
export default Layout;

And below mentioned is my Auxilary ponent code:

const Aux = ( props ) => props.children;
export default Aux;

When I am invoking LayoutComponent from my App.js render() method, the JSX content inside tag is not getting displayed.

If I replace the tag with tag then it is working fine, but I don't need that extra div in my DOM structure.

The DOM is shown something like this in chrome if I use Aux tag.

Please Help.

Share Improve this question edited May 29, 2018 at 12:36 bennygenel 24.7k7 gold badges67 silver badges79 bronze badges asked May 29, 2018 at 12:31 Anand GuptaAnand Gupta 3662 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

The problem is that a ponent must return exactly one direct child. In React, this was solved recently by introducing Fragments, but this feature is currently not supported in Preact yet. If you are sure that the ponent will only have one child, you could insert it like this:

const Aux = (props) =>
  props.children.length === 1 && props.children[0];

However, since you want to insert two children in your example, the only way is indeed to wrap them in a div or any other tag like so:

const Aux = (props) => (
  <div>
    { props.children }
  </div>
);
const aux = (props) => props.children;
export default aux;

just two line! :D

发布评论

评论列表(0)

  1. 暂无评论