[英]RN - How to create components and put other components in it
I'm trying to create a custom component and put other components like or inside this component but it doesn't seem to be working (nothing shows up).我正在尝试创建一个自定义组件并将其他组件像该组件一样或放在该组件内,但它似乎不起作用(没有显示任何内容)。 Could someone be kind enough to provide an answer or perhaps correct my understanding where it's gone wrong?
有人可以提供答案或纠正我的理解哪里出了问题吗?
For example, if I have a Home
page and inside there's a Card
component where within there's Text
and View
components.例如,如果我有一个
Home
,里面有一个Card
组件,其中有Text
和View
组件。
import React from 'react'
import {Text, View} from 'react-native'
const CoolCard = ({props}) => {
return(
<View>
{props}
</View>
)
}
const Home = () => {
return(
<View>
<CoolCard>
<Text>This is a cool card!</Text>
</CoolCard>
</View>
)
}
export default Home
This doesn't work but if I do这不起作用,但如果我这样做
const Home = () => {
return(
<View>
<CoolCard props = {
<Text>This is a cool card!</Text>
}/>
</View>
)
}
this works, which I understand.这有效,我理解。 Is there a way for me to write the first example to make it work?
有没有办法让我编写第一个示例使其工作?
Thanks a lot!非常感谢!
You should use the 'children' prop to get the children您应该使用“儿童”道具来获取儿童
const CoolCard = ({children}) => {
return(
<View>
{children}
</View>
)
}
const Home = () => {
return(
<View>
<CoolCard>
<Text>This is a cool card!</Text>
</CoolCard>
</View>
)
}
export default Home
In order to "wrap" a component inside another you can use props.children this is how it looks in a react functional component :为了将一个组件“包装”在另一个组件中,您可以使用 props.children 这是它在 React 功能组件中的外观:
Wrapper component:包装组件:
const WrapComponent = ({children}) => (
<Text>
{children}
</Text>
)
Then you can wrap it around any valid JSX:然后你可以将它包裹在任何有效的 JSX 中:
<WrapComponent> {/* put stuff here */} </WrapComponent>
You can find more in the official react documentation您可以在官方react 文档中找到更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.