将道具传递给React Native中的屏幕

时间:2018-02-14 03:31:51

标签: reactjs react-native

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

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

由于

2 个答案:

答案 0 :(得分:0)

mediaUrl=https://qrstuff.com/vcard.download/dec91a6d6/yo_yo_ma_vCard.vcf的构造函数中,props应该能够通过

传递给HomeScreen
BaseComponent

它对你有用吗?

答案 1 :(得分:0)

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组件也是一个单独的可重用组件。

你需要将道具(在我们的情况下&#39;标题&#39;)从上层组件传递到基础组件,如上例所示。