【问题标题】:React Native element only visible/usable after pressing a buttonReact Native 元素仅在按下按钮后可见/可用
【发布时间】:2020-01-21 03:47:36
【问题描述】:

React Native 新手,正在尝试应用创意。基本上我只是想创建一个当我按下按钮时出现的 TextInput 元素。下面是我的尝试。我正在尝试利用课堂上的状态,但有些东西不对劲。

Expo 抛出“null 不是对象(评估 'this.state.isShowingText')”错误。

有什么想法吗?

import React, { Component } from 'react';
import { TextInput, Alert, Button, ScrollView, Text, View, StyleSheet } from 'react-native';

export default class CoolComponent extends Component {
  render() {
    const nameAdd = () =>{
      state = { isShowingText: true };
    }
    return (
      <View style={{ alignItems: 'center', top: 50 }}>
        <Title>Some Title</Title>
        {this.state.isShowingText ? <TextInput></TextInput> : null}
        <ScrollView></ScrollView>
        <Button
          title="Press me"
          onPress={nameAdd}
        />
      </View>
    );
  }
}

【问题讨论】:

    标签: react-native button state textinput


    【解决方案1】:

    你处理state的方式不对

    import React, { Component } from 'react';
    import { TextInput, Button, ScrollView, View } from 'react-native';
    
    export default class CoolComponent extends Component {
        state = {
            isShowingText: false
        }
    
        nameAdd = () => {
            this.setState({
                isShowingText: true
            })
        }
    
        render() {
            return (
                <View style={{ alignItems: 'center', top: 50 }}>
                    {this.state.isShowingText ? <TextInput style={{ width: '50', height: '50', borderWidth: 1 }}></TextInput> : null}
                    <ScrollView></ScrollView>
                    <Button
                        title="Press me"
                        onPress={this.nameAdd}
                    />
                </View>
            );
        }
    }
    

    希望这对您有所帮助。如有疑问,请随意。

    【讨论】:

    • @Steel 如果此答案解决了您的问题,请考虑接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多