我是 React 世界的新手,因此面临组件之间通信的问题。我们有一个 3 步登录屏幕,每个屏幕都有一个顶部横幅图像和主背景图像,页脚中也有几个链接。唯一的区别是在每个屏幕中我们将有不同的表单字段。假设在第一个屏幕中我们将有用户名和一个按钮,在第二个屏幕上有一些标签和一个文本字段,在最后一个屏幕中我们将有密码字段和一个图像。
所以我的计划是,我想创建一个具有常见元素的索引组件,例如我所说的页眉 Logo 、主图像和页脚。我想将 3 个屏幕的组件传递到其中,以便 Index 将渲染传递的组件,因此如果我传递第一个组件,它应该显示页眉 Logo 、主图像、页脚和第一个屏幕组件。
这是第一个调用 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>
);
}
}
最佳答案
您可以通过传递 <LoginForm />
来修复它组件而不是 LoginForm
.
但这对于 children 来说是一个很好的用例。属性:
在Login.js中,您可以渲染:
render() {
return (
<Index>
<LoginForm />
</Index>
);
}
然后您可以使用以下方式在 Index.js 中显示表单:
{this.props.children}
关于javascript - React Native 将一个组件传递给另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508477/