react-native复选框,当我按下该复选框时,如何使用该复选框进行选中或取消选中?

Kaz*_*oto 0 checkbox react-native

我想知道如何在react-native中选中和取消选中复选框?

我需要使用getInitialState和props吗?还是只需要使用复选框和onPress?

Jan*_*ang 5

这是一个快速且非常简单的实现。

import Icon from 'react-native-vector-icons/FontAwesome';

class MyCheckbox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checked: false
        }
    }

    toggle() {
        this.setState({checked: !this.state.checked});
    }

    render() {
        return (
            <TouchableWithoutFeedback onPress={this.toggle.bind(this)}>
                <View>
                    {this.state.checked ?
                         <Icon name="angle-left" size={16} color='#000000' />
                         :
                         null
                    }
                </View>
            </TouchableWithoutFeedback>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

使用onPress函数更新组件的状态。将其状态设置为checked = true或checked = false。