声明对象时,将本机发送道具反应到组件

时间:2018-03-01 20:23:54

标签: reactjs react-native

我试图在FooScreen中向我的componentsObject发送任何道具并将其用于组件中,但它不允许我使用它。

   const FooScreen = ({props}) => <Center><Text>{props}</Text></Center>;
const BarScreen = () => <Center><Text>Bar</Text></Center>;

const components = {
  Foo: FooScreen({name:'test1'}),
  Bar: BarScreen({name:'test2'}),
};

const Center = ({ children }) => (
  <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>{children}</View>
);


const pages = [
    { screenName: 'Foo', componentName: 'Foo' },
    { screenName: 'Bar', componentName: 'Bar' },
  ];

我在屏幕上将其作为道具发送,在其他屏幕中我尝试将其用作

class TabBarView extends Component {
constructor(props){
    super(props);
    this.state = {
        tabs: ''
    }
}
componentDidMount(){
    console.log(this.props)
}
componentWillMount(){
    console.log(this.props)
    const {pages,components} = this.props
    setTimeout(() => {
        const screens = {};
        pages.forEach(page => {
          screens[page.screenName] = { screen: components[page.componentName] };
        });
        this.setState({ tabs: TabNavigator(screens) });
      }, 2000);
    }

    render() {
      if (this.state.tabs) {
        return <this.state.tabs />;
      }
      return <View><Text>Loading...</Text></View>;
    }
}
它失败了,不让我这样做。 之后,我想在FooScreen中使用反应中的真实屏幕并将其设置为stackNavigator

我收到错误

  

路线的组成部分&#39; Foo&#39;必须是反应成分

1 个答案:

答案 0 :(得分:1)

我建议组件返回函数而不是React元素。为每个元素分配一个键很容易 不应在componentWillMount中使用setState,尤其是当存在导致副作用的计时器时。 出于效率原因,我在网上测试了下面的代码。如果您将div替换为View,将p替换为Text,则应该在React Native中使用。不要忘记import { Text, View } from 'react-native'

import React, { Component } from 'react';

const FooScreen = props => (
  <Center>
    <Text>{`[Foo] ${props.name}`}</Text>
  </Center>
);
const BarScreen = props => (
  <Center>
    <Text>{`[Bar] ${props.name}`}</Text>
  </Center>
);

const components = {
  Foo: (key) => <FooScreen name="test1" key={key} />,
  Bar: (key) => <BarScreen name="test2" key={key} />,
};

const Center = props => (
  <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
    {props.children}
  </View>
);

const pages = [ 'Foo', 'Bar' ];

export default class TabBardiv extends Component {
  state = {
    tabs: null,
  };

  componentDidMount() {
    console.log(pages);

    setTimeout(() => {
      this.setState({ tabs: pages });
    }, 2000);
  }

  render() {
    if (!this.state.tabs) {
      return (
        <View>
          <Text>Loading...</Text>
        </View>
      );
    }

    const screens = pages.map((page, index) => {
      const element = components[page];
      console.log(element);
      return element(index);
    });
    return screens;
  }
}