React Native将一个组件传递给另一个组件

时间:2019-06-08 17:05:29

标签: javascript reactjs react-native

是React世界的新手,因此面临组件之间通信的问题。我们有一个三步登录屏幕,每个屏幕都有一个顶部横幅图像和主要背景图像,页脚中也有很少的链接。唯一的区别是在每个屏幕中,我们将有不同的表单字段。可以说,在第一个屏幕中,我们将有用户名和一个按钮,在第二个屏幕中,我们将有一些标签和一个文本字段,在最后一个屏幕中,我们将有密码字段和一个图像。

所以我正在计划创建一个索引组件,该组件具有一些常见元素,例如我所说的标题徽标,主图像和页脚。而且我想将3个屏幕的组件传递到其中,以便Index将呈现传递的组件,因此,如果我通过第一个组件,则应显示标题徽标,主图像,页脚和第一个屏幕组件。

这是第一个调用Index并传递LoginForm的组件,但它不呈现传递的LoginForm组件,它仅显示Index组件的图像。 如何在Index组件中显示传递的LoginForm?

import { LoginForm } from "./shared-components/LoginForm";
import { Index } from "./shared-components/Index";

export class Login extends Component {
  constructor(prop) {
    super(prop);
    this.state = { username: "", password: "", result: [], isLoading: false };
  }

  render() {
    return <Index passedForm={LoginForm} />;
  }
}

这是索引组件

import React from "react";
import { Image, ImageBackground } from "react-native";
import { Container, Content, View } from "native-base";
export class Index extends React.Component {
  constructor(prop) {
    super(prop);
    this.state = { username: "", password: "", result: [], isLoading: false };
  }


  render() {
    return (
      <Container>
        <Content>
          <Image
            source={require("../assets/finastra_logo.jpg")}
            style={{
              maxHeight: 150,
              alignSelf: "center",
              maxWidth: 215,
              flex: 1
            }}
          />
          <ImageBackground
            resizeMode="cover"
            blurRadius={3}
            source={require("../assets/frond.jpg")}
            style={{ alignSelf: "stretch", height: 500, marginBottom: 20 }}
          >
            {this.props.passedForm}
          </ImageBackground>
        </Content>
      </Container>
    );
  }
}

2 个答案:

答案 0 :(得分:2)

您可以通过传递<LoginForm />组件而不是LoginForm来解决此问题。

但这是children属性的好用例:

在Login.js中,您可以呈现:

render() {
  return (
    <Index>
      <LoginForm />
    </Index>
  );
}

然后您可以使用以下方法在Index.js中显示表单:

{this.props.children}

答案 1 :(得分:0)

您可以将其传递给变量,然后使用该变量进行渲染

const PassedForm = this.props.passedForm;

然后像通常渲染组件一样渲染它

<PassedForm />