我正在React中创建一个ViewContainer,它仅用作一般背景,然后希望在其中放置一个Text组件。但是,文本不会以这种方式出现。但是,当我将文本放在ViewContainer的创建中时,它确实出现了。我希望ViewComponent具有通用性,并且不希望它绑定到特定的文本上。
ViewContainer.js:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default class ViewContainer extends Component {
render() {
return <View style = {styles.ViewContainer}><Text> Hello, this is Feed! </Text></View>
}
}
const styles = StyleSheet.create({
ViewContainer: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'stretch',
backgroundColor: 'mistyrose'
}
});
App.js:
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';
import ViewContainer from './app/components/ViewContainer'
export default class App extends Component {
render() {
return <ViewContainer><Text>Hello, this is my new app!</Text> </ViewContainer>
}
}
以上内容不呈现文本。但是,如果我将文本组件放在ViewContainer内的View内部,它可以工作,但是我不想这样做。帮助将不胜感激!
答案 0 :(得分:1)
您需要了解的是children
。
将组件放置在另一个组件中时,就像在App
中所做的那样。该组件将位于this.props.children
中。
<ViewContainer>
{// inside ViewContainer component, whatever is inside here will be in this.props.children}
<Text>Hello, this is my new app!</Text>
</ViewContainer>
因此,要渲染ViewContainer
内部的内容,您需要渲染this.props.children
。
export default class ViewContainer extends Component {
render() {
// this will render anything that is inside ViewContainer
return <View style = {styles.ViewContainer}>{this.props.children}</View>
}
}