程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将 React 组件分解为“构建块”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决将 React 组件分解为“构建块”?

开发过程中遇到将 React 组件分解为“构建块”的问题如何解决?下面主要结合日常开发的经验,给出你关于将 React 组件分解为“构建块”的解决方法建议,希望对你解决将 React 组件分解为“构建块”有所启发或帮助;

我在我的应用程序中使用了 IonSlIDes,但由于使用了 bug,动态添加幻灯片可能会很困难。 因为 IonSlIDes 是建立在 SwiperJs 之上的,所以它有一些添加和删除幻灯片的方法。这些的缺点是它们采用带有 HTML 的字符串。就我而言,我需要能够传入 JsX 元素,以便我可以对它们使用事件侦听器。最初,这是我的代码:

private bindEvents(el: JsX.Element): voID {
    if (el.props.children) { //checking if the element actually has children
        const children = this.toArray(el.props.children); //If it has only 1 child,it is an object,so this just converts it to an array

        children.forEach((c: any) => {
            if (!c.props) return; //Ignore if it has no props

            const propnames = this.toArray(Object.keys(c.props)); //Get the key names of the props of the child
            const el = $(`.${C.props.classnamE}`); //Find the element in the DOM using the class name of the child

            propnames.forEach(p => { //Binds the actuall events to the child.
                if (Events[p] !== undefined) {
                    el.on(Events[p],c.props[p]); //`c.props[p]` is the handler part of the event
                }
            });
        });
    }
}

通过调用:

appendSlIDe(slIDes: JsX.Element | JsX.Element[]): voID {
    if (this.slIDeRef.current === null) return;

    this.slIDeRef.current.getSwiper().then(sw => {
        slIDes = this.toArray(slIDes);

        slIDes.forEach(s => {
            sw.appendSlIDe(ReactDOMServer.renderToString(s));

            this.bindEvents(s);
        });
    });
}

当使用 IonSlIDe 调用 appendSlIDe 时,这非常有效:

x.appendSlIDe(<IonSlIDe>
    <div onClick={() => console.log("Clicked!")}</div>Click me!</IonSlIDe>

如果你点击了 div,它会打印出“Clicked!”。

但是,如果您传入自定义组件,它会中断。这是因为自定义组件不会显示 props 下的子组件。拿这个组件:

interface Props {
    test: String,}

const TestSlIDe: React.FC<Props> = (props) => {

    return (
        <IonSlIDe>
            <div>
               {props.String}
            </div>
        </IonSlIDe>
    );
}

如果您要打印该组件的道具,您会得到:

props: {test: "..."}

而不是像我在 bindEvents 函数中那样访问组件的子组件。

有两种方法可以解决这个问题。一种是获取组件的 Js 对象表示,就像这样(我记得很久以前偶然做了这个,但我不记得我是怎么得到的):

{
  type: 'IonSlIDe',props: {
    children: [{
      type: 'div',props: {
        children: ["..."],},}
  },}

或者,稍微妥协,将自定义组件解构为“构建块”。就 TestSlIDe 而言,这会将其解构为 IonSlIDe 组件。

我尝试了几个小时,但没有成功。我真的很感激这方面的帮助。

解决方法

无论出于何种原因有人需要它,我发现您可以执行 el.type(el.props) 其中 el 是一个 JSX 元素。 这将创建元素的一个实例,因此在 children 下,您可以看到组件的实际子组件,而不是看到 props。

大佬总结

以上是大佬教程为你收集整理的将 React 组件分解为“构建块”全部内容,希望文章能够帮你解决将 React 组件分解为“构建块”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: