代码之家  ›  专栏  ›  技术社区  ›  kwoxer

如何通过在React中单击按钮来设置父级的状态

  •  1
  • kwoxer  · 技术社区  · 4 年前

    我想设置 title 当我点击另一个屏幕上的按钮时,我的屏幕会被设置为特定值。

    所以我最后想实现的是以下几点。从我的 HomeScreen 我得到一个 ChangeScreen 在那里我可以保存用户配置文件。现在,当用户提交其 name ,例如,该名称应显示在标题中。

    我仍然怀念数据传输的部分 更改屏幕 App.js .

    我已经发现了非常相似的问题,但我无法应用这些解决方案:

    找到我的零食 here .

    App.js

    import * as React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    import Home from './components/HomeScreen';
    import Change from './components/ChangeScreen';
    import { NavigationContainer } from '@react-navigation/native'
    import { createStackNavigator } from '@react-navigation/stack'
    const Stacks = createStackNavigator();
     
    class App extends React.Component {
      state = {
        newtitle : 'foo'
      }
      
      handleLoginnameChange = newtitle => {
        this.setState({ newtitle })
      }
    
      render() {
        return (
          <NavigationContainer>
            <Stacks.Navigator
              headerMode="screen"
              screenOptions={{
                //headerTitle: this.state.newtitle,
                //headerTitle: props => <Change {...props} />
              }}
            >
            <Stacks.Screen
              name="home"
              component={Home}
              options={
                { 
                  title: 'Home'
                }
              }
            />
            <Stacks.Screen
              name="change"
              component={Change}
              options={
                { 
                  title: 'Change' 
                }
              }
            />
            </Stacks.Navigator>
          </NavigationContainer>
        );
      }
    }
    
    export default (App);
    

    HomeScreen.js

    import React from 'react'
    import { Button, Text, View } from 'react-native';
    
    class HomeScreen extends React.Component {
      render() {
        return (
          <View> 
            <Text>Hi, this is a test of change the title from another component</Text>
            <Button title='To the Change title screen' onPress={() => this.props.navigation.navigate('change')}>Change</Button>
          </View>
        ); 
      }
    }
    export default HomeScreen;
    

    ChangeScreen.js

    import React from 'react'
    import { Button, Text, View } from 'react-native';
    
    class ChangeScreen extends React.Component {
      render() {
        return (
          <View>
            <Text>Clicking this button will change the Header title to "TEST" and going back to Home.</Text>
            <Button title='Save' onPress={() => this.props.navigation.navigate('home')}>Home</Button>
        // on that button I need the setState or something similar like a onChange or onClick handler
          </View>
        );
      }
    }
    export default ChangeScreen;
    
    0 回复  |  直到 4 年前