【问题标题】:React Native pass one component to another componentReact Native 将一个组件传递给另一个组件
【发布时间】:2019-10-23 19:07:21
【问题描述】:

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

所以我的计划是我想创建一个索引组件,其中包含我所说的页眉徽标、主图像和页脚等常见元素。我想将 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>
    );
  }
}

【问题讨论】:

  • 我的猜测是:你通过了课程。尝试实例化它。
  • @RadosławCybulski:怎么样?

标签: javascript reactjs react-native


【解决方案1】:

您可以通过传递 &lt;LoginForm /&gt; 组件而不是 LoginForm 来修复它。

但这是 children 属性的一个很好的用例:

在Login.js中,可以渲染:

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

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

{this.props.children}

【讨论】:

    【解决方案2】:

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

    const PassedForm = this.props.passedForm;
    

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

    <PassedForm />
    

    【讨论】:

      猜你喜欢
      • 2019-07-17
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      相关资源
      最近更新 更多