首页 > 解决方案 > TSX:阅读子孙的道具

问题描述

我正在尝试创建一个包装组件,它将在 React 中为我创建选项卡(使用打字稿),但我发现了一些我无法解决的困难。

我想我陷入了困境,因为我有这个要求,如果我们选择删除选项卡式显示,而让孩子自己独立,那仍然必须在语义和逻辑上正确并以非表格形式呈现方法。

因此,包装组件只需要孩子。没有道具,什么都没有,只有孩子。包装组件称为 TabBar,我正在传递一些孩子:

    <TabBar>
       <section>
          <h2>
              <button>
                 Tab title
              </button>
          </h2>
          <div>
               Content
          </div>
      </section>
    </TabBar>

上面的示例接收该部分作为一个孩子。

如果我注销孩子,我会得到一个长度为 1 的数组,其中有道具和孩子,还有孩子等等。

如果我 console.log 上面的例子,这是我收到的孩子的例子:

[
        {
            type: "section",
            props: {
                children: [
                    {
                        type: "h2",
                        props: {
                            props: {
                                children: "Tab title"
                            }
                        }
                    },
                    {
                        type: "div",
                        props: {
                            children: "Content"
                        }
                    }
                ]
            }
        }
    ]

现在我需要做的是,以某种方式访问​​儿童和他们的孙子的道具,深入几层。

如果我控制台注销 ~~别看这太可怕了,而且只是一个概念证明~~: console.log(children[0].props.children[0].props.children.props.children);

我得到了我所期望的:“标签标题”。

问题是,根据 VS 代码,children[0].props

Property 'props' does not exist on type 'string | number | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | ReactNodeArray | ReactPortal'. Property 'props' does not exist on type 'string'.

我怎么能告诉 typescript 是的……道具在那里,别吓坏了?

标签: reactjstypescript

解决方案


推荐阅读