gpt4 book ai didi

javascript - React Native 如何在组件之间传递数据

转载 作者:行者123 更新时间:2023-11-29 23:27:36 26 4
gpt4 key购买 nike

我想知道在 React Native 中单击按钮时如何从组件获取数据并将其传递给其他组件。这是我的代码:

这是我的输入组件:

ZipInput.js

import React from 'react';
import { TextInput } from 'react-native';
import styles from './../assets/style';


export default class ZipInput extends React.Component {

constructor(props) {
super(props);
this.state = '';
}

render() {
return (
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({text})}
keyboardType={'numeric'}
placeholder = {'Enter Zip Code'}
/>
);
}
}

这是我的按钮:

GoButton.js

import React from 'react';
import { Button, View } from 'react-native';
import styles from './../assets/style';
import {StackNavigator} from 'react-navigation';


export default class GoButton extends React.Component {
_handlePress(event) {
alert('Pressed!');
}

render() {
const {navigate} = this.props.navigateProp
return (
<View style={styles.buttonContainer}>
<Button
onPress={() =>
navigate('ZipResultScreen')
}
title="GO"
accessibilityLabel="Find Insurance Quotes"
color='#fff'
/>
</View>

);
}
}

我 serparetely 创建了组件并将它们导入到 Homescreen.js 中。我将从那里将数据传递给其他组件。

这是我的 Homescreen.js:

import React from 'react';
import { StyleSheet, Text, View, ImageBackground } from 'react-native';
import styles from '../assets/style'
import Header from '../components/header';
import ZipInput from '../components/zipinput';
import InsuranceType from '../components/insurancetype';
import GoButton from '../components/gobutton';
import {StackNavigator} from 'react-navigation';


export default class HomeScreen extends React.Component {
render() {
const navigate = this.props.navigation;
return (
<View style={styles.container}>
<Header />
<ImageBackground
style={styles.imgbg}
source={{ uri: 'https://www.expertinsurancereviews.com/wp-content/uploads/2017/03/background-hp-1.jpg' }}
>
<View style={styles.intro}>
<Text style={styles.title}>Compare Insurance Rates</Text>
<ZipInput />
<InsuranceType style={styles.select} />
<GoButton navigateProp = {navigate} />
</View>

</ImageBackground>
</View>
);
}
}

最佳答案

您需要在导航到另一个屏幕时传递您的数据。

考虑以下示例。

<Button onPress={() => navigation.navigate('ScreenName', { data: { title: 'Hello World'} })}>

export default class Screen extends React.Component {
render () {
const { title } = this.props.navigation.state.params.data

return (
<View>
<Text>{title}</Text>
</View>
)
}
}

关于javascript - React Native 如何在组件之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com