微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我怎样才能通过短方式控制道具?

如何解决我怎样才能通过短方式控制道具?

我想知道我们怎样才能让这个案例变得容易?

我有一个自定义的 Typeahead 组件,这将使我的一些自定义操作。所以我想通过TypeaheadCustom组件的props来控制Typeahead的props:

在组件中我调用 TypeaheadCustom :

<TypeaheadCustom propsControler />

在 TypeaheadCustom 组件中:

function TypeaheadCustom({ propsControler,children,...otherProps },ref) {
    if(propsControler=== true) { //make some propsOfTypeahead}
        return (
            <Fragment>
                <Typeahead ref={ref} {...otherProps} //propsOfTypeahead>
                    {children}
                </Typeahead>
            </Fragment>
        );
    }
}

我想要这样做,因为我想要它干净。我们怎么做?谢谢

解决方法

您可以为此编写一个 HoC。在 HoC 中,您传递了 propsControler。如果为真,则返回组件,否则返回 null。这是伪代码

`

function TypeaheadCustom(propsControler,childrenComponent,ref) {
    return propsControler === true ? (<Fragment>
        <Typeahead ref={ref} {...otherProps}> //propsOfTypeahead>
        {<childrenComponent />} // It shall have the props of its own 
            </Typeahead>
    </Fragment>) : null
}
}

`

,

您可以在条件内创建对象,并将该对象作为道具传递

function TypeaheadCustom({ propsControler,children,...otherProps },ref) {
    if(propsControler=== true) { 
        const propsOfTypeahead = {prop1: 1,prop2: 2}
        return (
            <Fragment>
                <Typeahead ref={ref} {...otherProps} {...propsOfTypeahead}>
                    {children}
                </Typeahead>
            </Fragment>
        );
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。