React Native-我们如何知道孩子是否包含 或来自父母的 ?

问题描述 投票:1回答:2

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

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}
      />
    )
  }
}
//Use with text
<CustomComponent>
  <View>
    <Image {passing image} />
    <Text>Sample</Text>
  </View>
</CustomComponent>

但是现在我需要处理children是否仅将<Images/><Text>传递,有什么建议吗?

reactjs react-native custom-component
2个回答
2
投票

如果有多个元素,则props传递的children实际上是array

children:  

[0]: <Image {passing image} />
[1]: <Text>Sample</Text>

如果您按照以下方式排列子元素,并且结构是固定的。

  <View>
    <Image {passing image} />
    <Text>Sample</Text>
  </View>

您可以通过(可能带有optional chaining来访问)子级的子级数组

this.props.children.props.children[1].type === 'Text'

这意味着在您的情况下,您可以检查其长度,或者第二个元素的类型是否适合Text,以确定是否传递了Text组件。

[在线试用:

Edit nervous-monad-jfkhz


更新

如果我们想要子视图的完整视图,则不带属性type的控制台会很好。

this.props.children.props.children[1]
type: "div"
key: null
ref: null
props: Object
_owner: FiberNode
_store: Object

0
投票

[当我们将道具作为孩子传递时,孩子可以是任何React.Node,这使得很难确定孩子到底是什么,也不可靠。检查children.props.children [1] .type是不可靠的,因为如果有人重新排列子级的结构可能不起作用。

在您的情况下,我们需要使CustomComponent接受两个道具:1张图片2文字并使它对于不需要的任何内容都可以为空。然后,在您的customComponent中,我们可以访问实际的图像和文本组件。如果要访问HTMLElement而不是节点,则可以将ref传递给图像和文本组件,然后可以在CustomComponent中访问当前值

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

const CustomComponent = ({ image, text }) => {
 if (image !== null) {
    ...
 }
 if (text !== null) {
    ...
 }
 return (
   <View>
    {image}
    {text}
   </View>
 )
} 

然后您就这样使用它

 <CustomComponent 
  image={<Image src='' />}
  text={<Text>Sample</Text>} 
 /> 
© www.soinside.com 2019 - 2024. All rights reserved.