Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native 基于状态的条件呈现不处理状态更改_React Native - Fatal编程技术网

React native 基于状态的条件呈现不处理状态更改

React native 基于状态的条件呈现不处理状态更改,react-native,React Native,我的状态中有一个值,该值根据开关而变化。根据状态项的值,我想更改按钮的样式。我可以看到状态改变,但颜色没有改变 这似乎很简单,如本文档所示: 我实际上有一个条件呈现在同一个语句中工作,但它引用的是redux状态而不是组件状态 我已经在下面介绍了代码的相关方面,并试图去掉不必要的东西 还是有点长 /* eslint-disable prettier/prettier */ import React, { Component } from 'react'; import { View,

我的状态中有一个值,该值根据开关而变化。根据状态项的值,我想更改按钮的样式。我可以看到状态改变,但颜色没有改变

这似乎很简单,如本文档所示:

我实际上有一个条件呈现在同一个语句中工作,但它引用的是redux状态而不是组件状态

我已经在下面介绍了代码的相关方面,并试图去掉不必要的东西

还是有点长

/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import {
    View,
    Text,
    TouchableOpacity,
    Dimensions,
    StyleSheet,
    TextInput,
    Switch,
    ActivityIndicator,
} from 'react-native';
import { connect } from 'react-redux';

// Actions
import { createUser } from '../../actions/user-actions';

// Getting dims
const { width: WIDTH } = Dimensions.get('window');

// Styling
const styles = StyleSheet.create({
    containerStyle: {
        flex: 1,
        backgroundColor: 'black',
        alignItems: 'center',
        justifyContent: 'center',
    },
    footerContainerStyle: {
        justifyContent: 'flex-start',
        flex: 3,
        width: WIDTH,
        paddingHorizontal: 30,
        alignItems: 'center',
        marginTop: 45,
    },
    tcStyle: {
        flexDirection: 'row',
        marginBottom: 20,
    },
    switchStyle: {
        marginRight: 15,
    },
    buttonStyle: {
        width: WIDTH-100,
        height: 50,
        backgroundColor: '#007AFF',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 20,
    },
    disabledButtonStyle: {
        width: WIDTH-100,
        height: 50,
        backgroundColor: '#007AFF',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 20,
        opacity: 0.3,
    },
    buttonTextStyle: {
        color: 'white',
        fontSize: 14,
        fontWeight: 'bold',
    },
    linkStyle: {
        textDecorationLine: 'underline',
        color: 'blue',
    },
});

// Component
class Signup extends Component {
    constructor(props) {
        super(props);
        this.state = {
            switchValue: false,
            email: '',
            name: '',
            password: '',
            passwordConfirm: '',
            errorMessage: '',
        };
    }

    componentDidUpdate() {
        console.log(this.props.users);
        const { navigation } = this.props;
        if (this.props.users.user) {
            navigation.navigate('Home');
        }
    }

    componentDidMount() {
        console.log(this.props);
    }

    // Helper functions
    toggleSwitch = (value) => {
        this.setState({switchValue: value});
    };

    onSignUp = () => {
        const { email, name, password, passwordConfirm, switchValue } = this.state;

        const { createUser } = this.props;

        if (password !== passwordConfirm) {
            console.log('Passwords do not match')
            this.setState({errorMessage: 'Passwords do not match'});
            return;
        }

        if (!switchValue) {
            console.log('You must agree to terms');
            this.setState({errorMessage: 'You must agree to terms'});
            return;
        }

        createUser(email, password, name);
    }

    render() {
        // Conditional button rendering
        const { email, password, passwordConfirm, name, switchValue } = this.state;
        let button;
        console.log(switchValue);

        if (this.props.users.loading) {
            button = (
                <TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
                    <ActivityIndicator size="large" />
                </TouchableOpacity>
            );
        } else if (switchValue) {
            button = (
                <TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
                    <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
                </TouchableOpacity>
            )
        } else if (!switchValue) {
            button = (
                <TouchableOpacity style={[styles.disabledButtonStyle]} onPress={this.onSignUp}>
                    <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
                </TouchableOpacity>
            )
        }

        return (
            <View style={styles.containerStyle}>
                <View style={styles.footerContainerStyle}>
                    <View style={styles.tcStyle}>
                        <Switch
                            onValueChange = {this.toggleSwitch}
                            value = {this.state.switchValue}
                            style = {styles.switchStyle}
                            trackColor={{true: '#007AFF', false: 'grey'}}
                        />
                        <Text style={{color: 'white', flexWrap: 'wrap', flex: 1}}>I have read & agree to the <Text style={styles.linkStyle}>Terms of Use</Text> and <Text style={styles.linkStyle}>Privacy Policy</Text></Text>
                    </View>

                    {button}

                    <View style={styles.textLinkStyle}>
                        <Text style={styles.ctaHelpTextStyle}>Have an account?</Text>
                        <TouchableOpacity>
                            <Text style={styles.ctaTextStyle}> Sign In</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
}

// state mapping
const mapStateToProps = ({ users }) => ({
    users,
});

// Export
export default connect(mapStateToProps, {
    createUser,
})(Signup);
/*eslint禁用prettier/prettier*/
从“React”导入React,{Component};
进口{
看法
文本,
可触摸不透明度,
尺寸,
样式表,
文本输入,
转换
活动指示器,
}从“反应本机”;
从'react redux'导入{connect};
//行动
从“../../actions/user actions”导入{createUser};
//变暗
const{width:width}=Dimensions.get('window');
//造型
const styles=StyleSheet.create({
集装箱运输方式:{
弹性:1,
背景颜色:“黑色”,
对齐项目:“居中”,
为内容辩护:“中心”,
},
页脚容器样式:{
justifyContent:“flex start”,
弹性:3,
宽度:宽度,
水平方向:30,
对齐项目:“居中”,
玛金托普:45,
},
tcStyle:{
flexDirection:'行',
marginBottom:20,
},
开关样式:{
marginRight:15,
},
按钮样式:{
宽度:宽度-100,
身高:50,
背景颜色:“#007AFF”,
边界半径:4,
对齐项目:“居中”,
为内容辩护:“中心”,
marginBottom:20,
},
禁用按钮样式:{
宽度:宽度-100,
身高:50,
背景颜色:“#007AFF”,
边界半径:4,
对齐项目:“居中”,
为内容辩护:“中心”,
marginBottom:20,
不透明度:0.3,
},
ButtonExtStyle:{
颜色:'白色',
尺寸:14,
fontWeight:'粗体',
},
链接样式:{
textDecorationLine:“下划线”,
颜色:“蓝色”,
},
});
//组成部分
类注册扩展了组件{
建造师(道具){
超级(道具);
此.state={
switchValue:false,
电子邮件:“”,
名称:“”,
密码:“”,
密码确认:“”,
错误消息:“”,
};
}
componentDidUpdate(){
console.log(this.props.users);
const{navigation}=this.props;
if(this.props.users.user){
导航。导航(“主页”);
}
}
componentDidMount(){
console.log(this.props);
}
//辅助函数
toggleSwitch=(值)=>{
this.setState({switchValue:value});
};
onSignUp=()=>{
const{email,name,passwordConfirm,switchValue}=this.state;
const{createUser}=this.props;
如果(密码!==密码确认){
console.log('密码不匹配')
this.setState({errorMessage:'密码不匹配'});
返回;
}
if(!switchValue){
console.log(“您必须同意条款”);
this.setState({errorMessage:'您必须同意条款'});
返回;
}
createUser(电子邮件、密码、名称);
}
render(){
//条件按钮渲染
const{email,password,confirm,name,switchValue}=this.state;
让按钮;
console.log(开关值);
if(this.props.users.loading){
按钮=(
);
}else if(开关值){
按钮=(
创建帐户
)
}如果(!switchValue){
按钮=(
创建帐户
)
}
返回(
我已阅读并同意使用条款和隐私政策
{按钮}
有账户吗?
登录
);
}
}
//状态映射
常量mapStateToProps=({users})=>({
用户,
});
//出口
导出默认连接(MapStateTops{
createUser,
})(注册);

如果我切换该开关,我希望按钮组件更改为具有其他样式的组件。但这并没有发生。

例如,添加返回条件

if (this.props.users.loading) {
      return(
         <TouchableOpacity style={[styles.buttonStyle]} onPress{this.onSignUp}>
            <ActivityIndicator size="large" />
        </TouchableOpacity>
   );
  }
if(this.props.users.load){
返回(
);
}

根据您的代码,两个按钮之间的唯一区别只是样式。 我的方法是简单地使样式中的条件本身而不是渲染方法本身上的if语句,如下所示:


解决方案 修改此片段:

// ... Other code parts

if (this.props.users.loading) {
    button = (
        <TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
            <ActivityIndicator size="large" />
        </TouchableOpacity>
    );
} else if (switchValue) {
    button = (
        <TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
            <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
        </TouchableOpacity>
    )
} else if (!switchValue) {
    button = (
        <TouchableOpacity style={[styles.disabledButtonStyle]} onPress={this.onSignUp}>
            <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
        </TouchableOpacity>
    )
}
/。。。其他代码部分
if(this.props.users.loading){
按钮=(
);
}else if(开关值){
按钮=(
创建帐户
)
}如果(!switchValue){
按钮=(
创建帐户
)
}
为此:

// ... Other code parts

if (this.props.users.loading) {
    button = (
        <TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
            <ActivityIndicator size="large" />
        </TouchableOpacity>
    );
} else {
    button = (
        <TouchableOpacity style={switchValue ? styles.buttonStyle : styles.disabledButtonStyle} onPress={this.onSignUp}>
            <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
        </TouchableOpacity>
    )
}
/。。。其他代码部分
if(this.props.users.loading){
按钮=(
);
}否则{
按钮=(
创建帐户
)
}

希望这有帮助

实际上,您的状态更改正确,但不透明度不起作用

更新:

似乎react native在更改TouchableOpacity的o时遇到了问题
 else if (switchValue) {
      button = (
        <View opacity={0.5}>
          <TouchableOpacity style={styles.buttonStyle} onPress={this.onSignUp}>
            <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT true</Text>
          </TouchableOpacity>
        </View>
      );
    } else if (!switchValue) {
      button = (
        <View opacity={0.1}>
          <TouchableOpacity
            style={styles.disabledButtonStyle}
            onPress={this.onSignUp}
          >
            <Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT false</Text>
          </TouchableOpacity>
        </View>
      );