如何访问 React.Children 或 props.children 中的数据?
How to access data in React.Children or props.children?
所以我正在尝试从 props.children
或 React.Children
获取一些数据,但我做不到,这就是我正在做的事情:
console.log(props.children)
这会在控制台上打印:
[
0: {
$$typeof: Symbol(react.element)
key: "slide-id-0"
props: {section: {…}, onChange: ƒ}
...
}
1: {
$$typeof: Symbol(react.element)
key: "slide-id-1"
props: {section: {…}, onChange: ƒ}
...
}
]
如果我尝试像这样遍历它:
React.Children.map(children, child => (
console.log(child)
))
我得到了两个对象:
0: {
$$typeof: Symbol(react.element)
key: "slide-id-0"
props: {section: {…}, onChange: ƒ}
...
}
1: {
$$typeof: Symbol(react.element)
key: "slide-id-1"
props: {section: {…}, onChange: ƒ}
...
}
现在,我想要访问对象内 props 组件内的部分,但如果我尝试这样做:
React.Children.map(children, child => (
console.log(child.props)
))
我收到这个错误:
Property 'props' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | JSXElementConstructor> | ReactNodeArray | ReactPortal'.
Property 'props' does not exist on type 'string'.ts(2339)
我如何访问该数据?
首先,您可以 returns 子项作为平面数组,使用 react-children-to-array 为每个子项分配键,然后使用 .map()
对其进行迭代
React.Children.toArray(props.children).map(({ props })=> console.log(props))
我终于搞定了,我用这个问题作为参考:React.Children.map recursively
我就是这样做的:
React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if (child.props) {
console.log(child.props.section)
}
})
所以我正在尝试从 props.children
或 React.Children
获取一些数据,但我做不到,这就是我正在做的事情:
console.log(props.children)
这会在控制台上打印:
[
0: {
$$typeof: Symbol(react.element)
key: "slide-id-0"
props: {section: {…}, onChange: ƒ}
...
}
1: {
$$typeof: Symbol(react.element)
key: "slide-id-1"
props: {section: {…}, onChange: ƒ}
...
}
]
如果我尝试像这样遍历它:
React.Children.map(children, child => (
console.log(child)
))
我得到了两个对象:
0: {
$$typeof: Symbol(react.element)
key: "slide-id-0"
props: {section: {…}, onChange: ƒ}
...
}
1: {
$$typeof: Symbol(react.element)
key: "slide-id-1"
props: {section: {…}, onChange: ƒ}
...
}
现在,我想要访问对象内 props 组件内的部分,但如果我尝试这样做:
React.Children.map(children, child => (
console.log(child.props)
))
我收到这个错误:
Property 'props' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | JSXElementConstructor> | ReactNodeArray | ReactPortal'. Property 'props' does not exist on type 'string'.ts(2339)
我如何访问该数据?
首先,您可以 returns 子项作为平面数组,使用 react-children-to-array 为每个子项分配键,然后使用 .map()
React.Children.toArray(props.children).map(({ props })=> console.log(props))
我终于搞定了,我用这个问题作为参考:React.Children.map recursively
我就是这样做的:
React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if (child.props) {
console.log(child.props.section)
}
})