如何在 TypeScript React 中迭代组件的子元素?

29

我该如何在TypeScript tsx文件中迭代React组件的子元素?

以下是有效的JSX示例:

public render() {
    return (
        <div>
            {React.Children.map(this.props.children, x => x.props.foo)}
        </div>
    );
}

然而,在 TypeScript 中,变量 x 的类型是 React.ReactElement<any> ,因此我无法访问 props。是否需要进行某种转换?

3个回答

31

使用any应该尽量避免,因为你会失去类型信息。

相反,在函数参数类型中使用React.ReactElement<P>

React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)

4
如果您想要孙子辈,它们在 child.props.children 中 :) - Gunar Gessner

22

然而,在 TypeScript 中,x 的类型是 React.ReactElement,因此我无法访问 props。我需要进行某种类型的转换吗?

是的。同时建议使用术语 "assertion"。一个快速的方法:

React.Children.map(this.props.children, x => (x as any).props.foo)

1
import React, {FC, Children, isValidElement } from "react"



 const MyComponent: FC = ({children}) => {
    // define component logic
    return ( 
    // children is a prop that passed to the component
    // second arg is a callback
    { Children.map(children, child => {
              // if child is a valid element, we can set attributes
              // you might need to add attributes dynamically
              if (isValidElement(child)) {
                return {
                  ...child,
                  props: {
                    ...child.props,
                    className:"Add className here"
                  }
                }
               }
              // if element is not valid just return child
              return child
    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接