Javascript React Native-我们如何知道父元素包含哪些子元素?

Javascript React Native-我们如何知道父元素包含哪些子元素?,javascript,reactjs,react-native,dom,custom-component,Javascript,Reactjs,React Native,Dom,Custom Component,我正在创建一个简单的自定义组件,它将在文本中设置动态高度和宽度 Class CustomComponent extends React.Component{ render(){ if(this.props.children){ if(this.state.isLoading){ console.log(this.props.children) //Here i want to know what JSX is passing

我正在创建一个简单的自定义组件,它将在文本中设置动态高度和宽度

Class CustomComponent extends React.Component{
  render(){
    if(this.props.children){
      if(this.state.isLoading){
        console.log(this.props.children)

        //Here i want to know what JSX is passing

        return(
          <View>
            <ActivityIndicator size={'large'}/>
          </View>
        )
      }
      return(
        <ImageBackground
          source={this.props.source}
        >
          {this.props.children}
        </ImageBackground>
      )
    } else if(this.state.isLoading){
      return(
        <View>
          <ActivityIndicator size={'large'}/>
        </View>
      )
    } else return(
      <Image
        source={this.props.source}
      />
    )
  }
}
类CustomComponent扩展了React.Component{
render(){
如果(本.道具.儿童){
if(此.state.isLoading){
console.log(this.props.children)
//这里我想知道JSX传递了什么
返回(
)
}
返回(
{this.props.children}
)
}else if(this.state.isLoading){
返回(
)
}否则返回(
)
}
}
//与文本一起使用
样品

但是现在我需要处理
子对象是否只通过
传递
,有什么建议吗?

如果有多个元素,道具传递的
子对象实际上是一个数组

children:  

[0]: <Image {passing image} />
[1]: <Text>Sample</Text>
这意味着在您的情况下,您可以检查它的长度,或者第二个元素的类型是否适合
文本
,以确定是否传递了
文本
组件

在线试用:


更新 如果我们想要孩子们的完整视图,不带属性
type
的控制台就好了

this.props.children.props.children[1]

当我们将道具作为子对象传递时,子对象可以是任何React.Node,这使得我们很难确定子对象到底是什么,也不可靠。正在检查children.props.children[1]。类型不可靠,因为如果有人重新排序子类型的结构,该类型可能无法工作

在您的情况下,我们需要使CustomComponent接受两个道具:

1-图像

2-文本

并使其对任何不需要的项都可以为null。 然后在customComponent中,我们可以访问实际的图像和文本组件。如果要访问HtmleElement not节点,可以将ref传递给图像和文本组件,然后可以访问CustomComponent中的当前值

示例:带有内嵌道具的功能组件

const CustomComponent = ({ image, text }) => {
 if (image !== null) {
    ...
 }
 if (text !== null) {
    ...
 }
 return (
   <View>
    {image}
    {text}
   </View>
 )
} 
constcustomcomponent=({image,text})=>{
如果(图像!==null){
...
}
如果(文本!==null){
...
}
返回(
{image}
{text}
)
} 
然后你就这样使用它

 <CustomComponent 
  image={<Image src='' />}
  text={<Text>Sample</Text>} 
 /> 


实际上我想从我的
CustomComponent
中传递的孩子那里得到全部JSX,所以在上面的例子中,我想在我的
CustomComponent
中控制台
Sample
,有可能吗?@flix我认为这与问题标题无关,你也可以使用
ref
createElement
来实现这一点,基于此,answer@flix您所指的
示例
儿童
相同,只是格式不同,请查看此处的相关文档
this.props.children.props.children[1]
type: "div"
key: null
ref: null
props: Object
_owner: FiberNode
_store: Object
const CustomComponent = ({ image, text }) => {
 if (image !== null) {
    ...
 }
 if (text !== null) {
    ...
 }
 return (
   <View>
    {image}
    {text}
   </View>
 )
} 
 <CustomComponent 
  image={<Image src='' />}
  text={<Text>Sample</Text>} 
 />