如何取消选择单选按钮?

时间:2018-10-17 02:52:47

标签: javascript react-native redux react-redux

页面加载后如何取消选择单选按钮。页面加载时,它正在选择第一个选项作为默认选项。这些是到目前为止我尝试过的代码。

register.js

class Register extends React.Component {
    constructor(props) {
        super(props);
        this.props.setSex('male', 'female');
    }

    render() {
         return (
            <View style={styles.container}>
                <Item style={{ height: 55 }}>
                    <View style={{ alignItems: 'flex-start', flexDirection: 'row' }}>
                          <Text style={{ fontSize: 18, color: '#fff' }}>{t('account_gender')}  </Text>
                          <RadioGroup flexDirection='row' style={{ color: '#fff' }} radioButtons={this.props.login.sex} onPress={() => this.props.onChangeSex()} />
                    </View>
               </Item>
            </View>
        );
    }
}

reducer.js

const initialState = {
    login :{
        sex: [
            {label: 'male', value: 1, size: 20, color: '#fff', selected: false},{label: 'female', value: 2, size: 20, color: '#fff', selected: false}
        ],
    }
}
export default function reducer (state = initialState, action){

    switch(action.type){
        case 'SETSEX' :
            let sex = {...state.login}
            sex.sex[0].label = action.male
            sex.sex[1].label = action.female
            return{
                ...state,
                login : sex
            }
        case 'CHANGESEX' :
            let selectedSex = state.login.sex.find(e => e.selected == true);
            selectedSex = selectedSex ? selectedSex.value : state.login.sex[0].label;
            return{
                ...state,
            }
}
return state
}

Actions / login.js

export function setSex(male, female) {
    return (dispatch) => dispatch({type: 'SETSEX', male, female})
}

export function onChangeSex() {
    return (dispatch) => dispatch({type: 'CHANGESEX'})
}

1 个答案:

答案 0 :(得分:0)

存在一些导致代码失败的问题。首先,像这样修改您的render()方法:

<RadioGroup flexDirection='row' style={{ color: '#fff' }} 
            radioButtons={this.props.login.sex} 
            onPress={ (data) => this.props.onChangeSex(data) } /> {/* Add data parameter */}

接下来,更新您的onChangeSex()调度程序以考虑添加的参数:

/* Add data parameter */
export function onChangeSex(data) {

    return (dispatch) => dispatch({type: 'CHANGESEX', data })
}

最后,更新您的reducer以考虑动作数据参数:

export default function reducer (state = initialState, action){

    switch(action.type){
        case 'SETSEX' : {
            let sex = {...state.login}
            sex.sex[0].label = action.male
            sex.sex[1].label = action.female
            return{
                ...state,
                login : sex
            }
        }
        case 'CHANGESEX' : {

            /* Update reducer */
            return{
                ...state,
                login : { sex : action.data }
            }
        }
     }

     return state
}

希望这会有所帮助!