我已经开始学习 React Native,并且一如既往地从创建可重用组件开始。我了解了如何在创建自定义组件时传递和访问 props。
我想在 React Native 中创建一个基本屏幕,它具有通用属性,并且我的应用程序中的所有屏幕都可以设置,例如标题。
下面我正在为我的应用程序的主页创建一个新屏幕
class APCComponent extends Component {
constructor(props) {
super(props);
}
render() { //dummy function, will always get overridden in the child
return (
<View />
);
}
}
export default class Home extends APCComponent {
//I somehow want to pass a string to the parent APCComponent
//and want APCComponent use it to set the Header of the navigation
constructor() {
super({ title: 'Home' });
}
//Right now the following works, but in case I use a different type of Navigation,
//I'll have to change all components. By just setting a string, I'm allowing my base
//component to display the header
static navigationOptions = { title: "Home" }; //from react-navigtion's StackNavigator
render() {
return <Button title="Sample Button" />;
}
}
Thanks
class BaseComponent extends Component {
render() {
return (){
<Header title={this.props.title} />
}
}
}
class HomeScreen extends Component {
render() {
return (){
<BaseComponent title='this is your home screen' />
}
}
}
where Header
组件也是一个单独的可重用组件。
您需要将 props(在我们的例子中为“title”)从上层组件传递到底层组件,如上面的示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)