在 React Native 中将道具传递给屏幕 [英] Passing Props to Screens in React Native

查看:29
本文介绍了在 React Native 中将道具传递给屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习 React Native,并且一如既往地从创建可重用组件开始.我学习了如何在创建自定义组件时传递和访问 props.

I have started to learn React Native and as always begin by creating reusable components. I learnt how you can pass and access props while creating custom components.

我想在 React Native 中创建一个基本屏幕,它具有通用属性并且我的应用程序中的所有屏幕都可以设置,例如标题.

I want to create a base screen in React Native, which has common properties and all screens in my app can set, like a title for example.

下面我正在为我的应用程序的主页创建一个新屏幕

Below I'm creating a new Screen for the home page of my app

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" />;
    }
}

谢谢

推荐答案

class BaseComponent extends Component {
  render() {
    return (){
      <Header title={this.props.title} />
    }
  }
}

class HomeScreen extends Component {
  render() {
    return (){
      <BaseComponent title='this is your home screen' />
    }
  }
}

其中 Header 组件也是一个单独的可重用组件.

where Header component is also a separate reusable component.

你需要像上面的例子一样将 props(在我们的例子中是'title')从上层组件传递到基础层组件.

you need to pass props(in our case 'title') from the upper level component to base level components like the above example.

这篇关于在 React Native 中将道具传递给屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆