javascript - react native -有办法隐藏/显示另一个页面中的项目吗?

标签 javascript reactjs react-native react-redux expo

我尝试通过标记“BOB”复选框来隐藏\显示“InfoTable”屏幕上的tableHead3:['BANANA'] 位于“SettingsScreen”中。 我是 React Native 的新手,我不知道 Redux。 有人可以告诉我如何用我的例子以简单的方式做到这一点吗?

this is the "OrderInformationScreen"

export default class OrderInformationScreen extends Component {

    constructor(props) {
        super(props);
        const { state } = props.navigation;
        this.state = {
            title: state.params.data //navprops.params.data.SHORT_TEXT
        }
        //alert(JSON.stringify((state.params.data.SHORT_TEXT)))
    }

    render() {
        return (
            <>
                <View
                    style={{
                        alignItems: 'flex-start',
                        justifyContent: 'center',
                        borderColor: 'blue',
                        flexDirection: "row",
                        justifyContent: 'space-evenly'
                    }}>
                    <TouchableOpacity onPress={() => console.log("cancel!")}>
                        <Avatar
                            size='large'
                            containerStyle={{ marginTop: 30 }}
                            activeOpacity={0.2}
                            rounded
                            source={require('../assets/down.png')} style={{ height: 80, width: 80 }}
                            onPress={() => console.log("cancel!")} />
                        <View >
                            <Text style={{ fontSize: 25, fontWeight: 'bold', color: 'red' }}>לדחות</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => console.log("works!")}>
                        <Avatar
                            size='large'
                            activeOpacity={0.1}
                            rounded
                            source={require('../assets/up.png')} style={{ height: 80, width: 80 }}
                            onPress={() => console.log("Works!")} />
                        <View>
                            <Text style={{ fontSize: 25, fontWeight: 'bold', color: 'green', marginHorizontal: 6 }}>לאשר</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <InfoTable headerInfo={this.state.title}></InfoTable>
            </>
        );
    };
}

this is the StackNavigator :

const PlacesNavigator = createStackNavigator({
    Main: MainScreen,
    MyTasks: MyTasksScreen,
    Settings: SettingsScreen,
    Sync: SyncScreen,
    Info: OrderInformationScreen
},
    {
        defaultNavigationOptions: {
            headerStyle: {
                animationEnabled: true,
                backgroundColor: Platform.OS === 'android' ? Colors.primary : ''
            },
            headerTintColor: Platform.OS === 'android' ? 'white' : Colors.primary,
        }
    }
);

export default createAppContainer(PlacesNavigator);

this is the "SettingsScreen"

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { CheckBox } from 'react-native-elements';


const SettingsScreen = props => {
    const [checked1, setChecked1] = useState(null);
    const [checked2, setChecked2] = useState(null);
    const [checked3, setChecked3] = useState(null);
    const [checked5, setChecked5] = useState(null);
    const [checked6, setChecked6] = useState(null);
    const [checked7, setChecked7] = useState(true);
    const [checked8, setChecked8] = useState(null);
    const handlePress = title => {


        if (title === 'LION') {  //6
            setChecked6(true), setChecked7(false), setChecked8(false)
        } else if (title === 'ZEBRA') {//7
            setChecked7(true), setChecked6(false), setChecked8(false)
        } else {
            setChecked8(true), setChecked7(false), setChecked6(false)
        }
    }
    useEffect(() => {
        setChecked7(true)
    }, [])


    return (
        <View>
            <CheckBox
                iconLeft
                checkedColor='red'
                title="LIZARD"
                checked={checked1}
                onPress={() => setChecked1(prev => !prev)}
            />
            <CheckBox
                iconLeft
                checkedColor='red'
                title="BIRD"
                checked={checked2}
                onPress={() => setChecked2(prev => !prev)}
            />
            <CheckBox
                iconLeft
                checkedColor='red'
                title="SNAKE"
                checked={checked3}
                onPress={() => setChecked3(prev => !prev)}
            />
            <CheckBox
                iconLeft
                checkedColor='red'
                title="SOUND"
                checked={checked5}
                onPress={() => setChecked5(prev => !prev)}
            />

            <CheckBox
                iconLeft
                checkedColor='green'
                title='LION'
                checkedIcon='dot-circle-o'
                uncheckedIcon='circle-o'
                checked={checked6}
                onPress={() => handlePress('LION')}
            />
            <CheckBox
                iconLeft
                checkedColor='green'
                title='ZEBRA'
                checkedIcon='dot-circle-o'
                uncheckedIcon='circle-o'
                checked={checked7}
                onPress={() => handlePress('ZEBRA')}
            />
            <CheckBox
                iconLeft
                checkedColor='green'
                title='BOB'
                checkedIcon='dot-circle-o'
                uncheckedIcon='circle-o'
                checked={checked8}
                onPress={() => handlePress('BOB')}
            />
        </View>

    );

};

SettingsScreen.navigationOptions = {
    headerTitle: 'SETTINGS'

};

export default SettingsScreen;

this is the "InfoTable" :

import React, { Component } from 'react';
import { StyleSheet, View, ScrollView } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import Swiper from 'react-native-swiper'


export default class InfoTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tableHead0: [`${this.props.headerInfo.SHORT_TEXT} (${(this.props.headerInfo.ORDERID).replace(/^0+/, '')})`],
            tableHead3: ['BANANA'],//THIS I WANT HIDE AND SHOW
            tableData3: [
                ['APPLE', `${this.props.headerInfo.COSTCENTER_TXT} (${(this.props.headerInfo.COSTCENTER)})`],
                ['MONKEY', `${this.props.headerInfo.LOC_WBS_ELEM_TXT} (${this.props.headerInfo.LOC_WBS_ELEM})`],
                ['FRIZ', `${this.props.headerInfo.SETTLORDER_TXT} (${this.props.headerInfo.SETTLORDER})`],
            ]
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.headerInfo != null) {
            this.setState({ tableHead0: [nextProps.headerInfo] })
        }
        alert(JSON.stringify(nextProps))
    }

    render() {
        const state = this.state;
        return (
            <Swiper style={styles.wrapper} showsButtons={true}>
                <ScrollView>
                    <View style={styles.container}>
                        <Table borderStyle={{ borderWidth: 2, borderColor: '#d83dff' }}>
                            <Row data={state.tableHead0} style={styles.head0} textStyle={styles.headText} />
                            <Row data={state.tableHead3} style={styles.head} textStyle={styles.headText} />
                            <Rows data={state.tableData3} textStyle={styles.text} />
                        </Table>
                    </View>
                </ScrollView>
            </Swiper>
        )
    }
}
const styles = StyleSheet.create({
    container: { flex: 1, backgroundColor: '#fff' },
    head0: { height: 80, backgroundColor: '#54beff' },
    head: { height: 40, backgroundColor: '#9febf5' },
    headText: { fontWeight: 'bold', fontSize: 20 },
    text: { margin: 10 },
});

最佳答案

使用AsyncStorage在设置屏幕中保存选中的单选按钮的值并在 InfoTable 中检索该值。

节省存储值(value)。

import {
 AsyncStorage,
 ...
} from 'react-native';

//save value in storage
const storeData = async (key, value) => {
  try {
    await AsyncStorage.setItem(key, value);
  } catch (error) {
    // Error saving data
  }
};

// retrieve value
retrieveData = async key => {
  try {
    const value = await AsyncStorage.getItem(key);
    if (value !== null) {
      // We have data!!
      return value;
    }
  } catch (error) {
    // Error retrieving data
  }
};

修改SettingsScreen中的handlePress

const handlePress = title => {
  if (title === 'LION') {
    //6
    setChecked6(true), setChecked7(false), setChecked8(false);

    // remove key from storage
    AsyncStorage.removeItem('checkbox').catch(e => console.log(e));
  } else if (title === 'ZEBRA') {
    //7
    setChecked7(true), setChecked6(false), setChecked8(false);
    // remove key from storage
    AsyncStorage.removeItem('checkbox').catch(e => console.log(e));
  } else {
    setChecked8(true), setChecked7(false), setChecked6(false);
    // add key to storage
    storeData('checkbox', 'tableHead3').catch(e => console.log(e));
  }
};

在InfoTable中从存储中获取值

state = {
  checkBoxKey: '', // used to store value from storage
  // I've added new object to store all the table data
  tableData: {
  tableHead0: [`${'SHORT_TEXT'} (${'ORDERID'})`],
  tableHead3: ['BANANA'], //THIS I WANT HIDE AND SHOW
  tableData3: [
    ['APPLE', `${'COSTCENTER_TXT'} (${'COSTCENTER'})`],
    ['MONKEY', `${'LOC_WBS_ELEM_TXT'} (${'LOC_WBS_ELEM'})`],

    ['FRIZ', `${'SETTLORDER_TXT'} (${'SETTLORDER'})`],
  ],
},
}

componentDidMount = async () => {
  try {
    const data = await this.retrieveData('checkbox');

    if (data) {
      this.setState(
        {
          checkBoxKey: data,
        },
        () => console.log(this.state.checkBoxKey)
      );
    }
  } catch (e) {
    console.log(e);
  }
};

在渲染中,从状态获取 checkBoxKey 并使用它来过滤表数据。

render = () => {
  const state = this.state;
  const tableData = state.tableData;

  const displayKeys = Object.keys(tableData).filter(key => {
    return key !== this.state.checkBoxKey;
  });

  return (
    <Swiper style={styles.wrapper} showsButtons={true}>
      <ScrollView>
        <View style={styles.container}>
          <Table borderStyle={{ borderWidth: 2, borderColor: '#d83dff' }}>
            {displayKeys &&
              displayKeys.map(key =>
                this.is2dArray(tableData[key]) ? (
                  <Rows data={tableData[key]} textStyle={styles.text} />
                ) : (
                  <Row data={tableData[key]} textStyle={styles.text} />
                )
              )}
          </Table>
        </View>
      </ScrollView>
    </Swiper>
  );
};

DEMO

关于javascript - react native -有办法隐藏/显示另一个页面中的项目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60360557/

相关文章:

页面加载代码上的 Javascript 使其重新加载 chrome 扩展

javascript - 更改 Text 元素 React 的内容

react-native - 我怎么知道要添加哪些 React Native pod subspecs?

javascript - 当我在页面之间浏览时,PDF.js 会引发事件吗?

javascript - 提交表单 javascript 之前确认警报

javascript - CodeMirror javascript 装订线行数字填充

javascript - React Server Side Rendering App - 如何更新元数据

javascript - 如何增加雷达 Chartjs 标签的大小和系列

javascript - 如何为响应式网页设计设计元素样式?

javascript - React.js - 是否可以在第一次渲染之前获取元素的大小?