为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只甜甜圈 2021-06-21 17:12:06
我是 React 世界的新手,所以我面临着组件之间的通信问题。我们有一个 3 步登录屏幕,每个屏幕都有一个顶部横幅图像和主背景图像,页脚中的链接也很少。唯一的区别是在每个屏幕中我们将有不同的表单字段。假设在第一个屏幕上我们将有用户名和一个按钮,在第二个屏幕上有一些标签和一个文本字段,在最后一个屏幕上我们将有密码字段和一个图像。所以我的计划是我想创建一个带有常见元素的索引组件,比如我说的页眉标志、主图像和页脚。我想将 3 个屏幕的组件传递到其中,以便索引将呈现传递的组件,因此如果我传递第一个组件,它应该显示标题徽标、主图像、页脚和第一个屏幕组件。这是第一个调用 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 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

您可以通过传递<LoginForm />组件而不是LoginForm.


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


在 Login.js 中,您可以渲染:


render() {

  return (

    <Index>

      <LoginForm />

    </Index>

  );

}

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


{this.props.children}


查看完整回答
反对 回复 2021-06-24
?
慕姐4208626

TA贡献1852条经验 获得超7个赞

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

const PassedForm = this.props.passedForm;

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

<PassedForm />


查看完整回答
反对 回复 2021-06-24
  • 2 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信