【问题标题】:OnPress change VIEW contentOnPress 更改 VIEW 内容
【发布时间】:2019-12-05 02:11:16
【问题描述】:

我希望顶部有两个标签按钮,下面有一些内容。

在那之后,我需要这样一个视图的内容:

<Form style={styles.form}>
    <Label style={styles.label}>
        data 1
    </Label>
    <Item >
        <Input/>
    </Item>
    <Label style={styles.label}>
        Data2
    </Label>
    <Item>
        <Input/>
    </Item>
</Form>

当我单击第一个按钮时,它处于活动状态。我需要那个表格出现。 之后,当我点击第二个按钮时,我需要将该表单更改为:

<Form style={styles.form}>
    <Label style={styles.label}>
        data 3
    </Label>
    <Item >
        <Input />
    </Item>
</Form>

我的理解是我需要一个状态变量。

state = {showFirst : true, showSecond:false }

并且在某处有条件:

if showFirst true, display FORM1
if showSecond true, display FORM2

还有

onPress {() => {this.setState{{the state = true)}}

但我不确定如何将它们绑定在一起,因为我是第一次使用 React Native。 目前我现在使用的是一个好习惯吗? 我为两种表单设置了单独的状态变量,因为稍后可能会添加另一个按钮。 所以我不能只有一个按钮:

state = { showForm: true}
showForm?Form1:Form2
onPress={() => {this.setState{{showForm:false)}}

我怎样才能让它工作?

【问题讨论】:

    标签: react-native button view


    【解决方案1】:

    这是你所说的你想要实现的最小示例组件:

    import React, {Component} from ‘react’;
    import {Button, View} from ‘react-native’;
    
    export default class ExampleComponent extends Component {
       constructor(props) {
          super(props);
          this.state = {
             showForm: 0
          };
        }
    
          render() {
             var form;
             if (this.state.showForm === 0) {
                form = (
                   <View> INSERT_FORM1 </View>
                );
             } else if (this.state.showForm === 1) {
                form = (
                   <View> INSERT_FORM2 </View>
                );
             }
    
             return (
                <View>
                   <Button title=‘Show Form 1’ onPress={() => this.setState({showForm: 0})}/>
                   <Button title=‘Show Form 2’ onPress{() => this.setState({showForm: 1})}/>
                   {form}
                </View>
             );
          }
    }
    

    您可以根据组件的道具和状态动态选择要显示的内容。
    在上面的示例中,我使用了一个数值来确定要显示的表单,以最大限度地减少您稍后必须跟踪的状态值的数量,如果表单计数扩大。 如果有更多可用的表单选择,switch 语句将是更好的选择,但我在这里使用了 if-else 以便于输入。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多