【问题标题】:How to select a single radio button at a time in react native flatlist如何在反应原生平面列表中一次选择一个单选按钮
【发布时间】:2019-09-05 22:28:26
【问题描述】:

我正在使用 react-native-radio-button 来实现一个带有单选按钮的平面列表,如图所示。

[![在此处输入图片描述][1]][1]

但我无法在平面列表中一次选择一个单选按钮。

这是我的代码

import React from 'react';
import { StyleSheet, View, Text, FlatList, TouchableOpacity, Image, LayoutAnimation, UIManager, Platform } from 'react-native';
import RadioButton from 'react-native-radio-button';
import PHARMACY from './api/mockPharmacyList';
import { Colors, Fonts } from '../../styles';

interface IState {
    selected: number;
    selectedIndex: number;
    data: any;
    expanded: boolean;
    checked: boolean;
}


export class TransferToPharmacy extends React.Component<{}, IState> {
    constructor(props) {
        super(props);
        this.state = {
            data: PHARMACY,
            selected: 0,
            selectedIndex: 0,
            expanded: true,
            checked: false,
        };
        this.onPress = this.onPress.bind(this);
        this.renderItem = this.renderItem.bind(this);
        this.renderSeparator = this.renderSeparator.bind(this);
        this._keyExtractor = this._keyExtractor.bind(this);
        this.changeLayout = this.changeLayout.bind(this);
        this.onCheck = this.onCheck.bind(this);

        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
    }

    changeLayout = () => {
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        this.setState({ expanded: false });
    }

    getInitialState() {
        return {
            value: 0,
        };
    }
    onPress(value) {
        this.setState({ selected: value });
    }

    _keyExtractor = (item, index) => item.id;

    onCheck = () => {
        const { checked } = this.state;
        if (checked === true) {
            this.setState({ checked: false  });
        } else {
            this.setState({ checked: true  });
        }
    }

    renderItem(data) {
        const { item } = data;
        return (
                <View style={styles.itemBlock}>

              <TouchableOpacity   >

                    <View style={styles.arrowIconStyle}>
                        <Text style={styles.pharmacyText}>{item.name}</Text>
                        <RadioButton
                            innerColor={Colors.darkBlue}
                            outerColor={Colors.lightGray}
                            animation={'bounceIn'}
                            isSelected={this.state.selectedIndex === 0}
                            onPress={this.onPress}
                        />
                    </View>
                    </TouchableOpacity>
                    <Text>{item.key1}</Text>

                 <View style={{ height: this.state.expanded === true ?  90 : 0, overflow: 'hidden' }}>

                        <View style={{ flexDirection: 'row', marginTop: 5, padding: 10 }}>
                             <Image style={[styles.itemImage, { width: 15, height: 15, margin: 1 }]} source={require('./images/map_pic_icon.png')} />
                             <Text style={styles.itemText}>{item.location}</Text>
                         </View>

                         <View style={{ flexDirection: 'row', marginTop: 5, padding: 10 }}>
                            <Image style={[styles.itemImage, { width: 15, height: 15, margin: 1 }]} source={require('./images/phone_icon.png')} />
                             <Text style={styles.itemText}>{item.phone}</Text>
                         </View>

                     </View>
                </View>
        );
    }

    renderSeparator() {
        return <View style={styles.separator} />;
    }
    render() {
        return (
            <View style={styles.container} >
                <Text style={styles.textStyle}>Transfer to Pharmacy</Text>

                <View style={styles.childViewStyle}>
                    <FlatList
                        keyExtractor={this._keyExtractor}
                        data={this.state.data}
                        renderItem={this.renderItem}
                        ItemSeparatorComponent={this.renderSeparator}
                    />
                </View>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    textStyle: {
        fontSize: 18,
        color: Colors.black,
        marginTop: 30,
        marginLeft: 20
    },
    childViewStyle: {
        margin: 20,
    },
    itemBlock: {
        paddingVertical: 15,
    },
    itemImage: {
        width: 50,
        height: 50,
        borderRadius: 25,
        margin: 10
    },
    itemText: {
        fontSize: 16,
        justifyContent: 'center',
        color: Colors.darkySkyBlue
    },
    itemName: {
        fontSize: 20,
        color: Colors.black,
    },
    separator: {
        borderRadius: 4,
        borderWidth: 1,
        borderColor: Colors.lightGray,
    },
    pharmacyText: {
        fontSize: 16,
        fontFamily: Fonts.bold,
        color: Colors.black

    },
    radioStyle: {
        marginTop: 10,
        marginRight: 50,
        justifyContent: 'space-between'
    },
    arrowIconStyle: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 10
        // flex: 1
    }
});

使用此代码我无法选择单选按钮

请让我知道哪里出了问题,因为我无法在平面列表中单独选择单选按钮。

我已经像这样改变了 onPress()

onPress( index) {
        this.setState({  selected: index, });
    }

在 renderItem 方法中我已经改变了它

const { item, index } = data;
 <RadioButton
                            innerColor={Colors.darkBlue}
                            outerColor={Colors.lightGray}
                            animation={'bounceIn'}
                            isSelected={this.state.selected === index}
                            onPress={() => this.onPress(index)}
                        />

现在输出是这样的

现在第一个单选按钮被选中,但是当我尝试选择其他单选按钮时,它们没有被选中。

这是我用于 Flatlist 的模拟数据文件。

export const PHARMACY = [
    {
        key: 0,
        name: 'Plaza Pharmacy',
        type: 'Urgent Care Center - 4.01 mi',
        location: '3417 Gaston Avenue, Suite 195\n Dallas, TX 75202',
        phone: '469.764.7100',

    },

    {
        key: 1,
        name: 'Courtyard Pharmacy',
        type: 'Urgent Care Center - 4.09 mi',
        location: '5236 West University Drive, Suite 1900\n MCKINNEY, TX 75071',
        phone: '969.264.7190',
    },
    {
        key: 2,
        name: 'Outptaient Pharmacy at the Cancer Center',
        type: 'Urgent Care Center - 4.66 mi',
        location: '3800 Gaylord Parkway, Ste 110\n FRISCO, TX 75034',
        phone: '890.664.8130',
    },
    {
        key: 3,
        name: 'Carrolton Pharmacy',
        type: 'Urgent Care Center - 4.08 mi',
        location: '5236 West University Drive, Suite 1900\n MCKINNEY, TX 75071',
        phone: '969.264.7190',
    },
    {
        key: 4,
        name: 'Garland Pharmacy',
        type: 'Urgent Care Center - 22.11 mi',
        location: '3417 Gaston Avenue, Suite 195\n Dallas, TX 75202',
        phone: '469.764.7100',
    },
];

我正在导出这个 const PHARMACY 并将其导入我的班级并将其设置为状态变量“数据”。

【问题讨论】:

  • 在您按下单选按钮时检查了记录了哪个值?原因是值索引值没有被传递给它

标签: react-native


【解决方案1】:

你可以在renderItem做这样的事情

renderItem = ({item, index}) => {
 .....
<RadioButton
  innerColor={Colors.darkBlue}
  outerColor={Colors.lightGray}
  animation={'bounceIn'}
  isSelected={this.state.selectedIndex === index}
  onPress={() => {this.onPress(index)}}
/>
}

并将onPress替换为

onPress = (index) => {
   this.setState({ selectedIndex: index });
 }

并将FlatList 更新为extraData propsFlatList 需要重新渲染为

<FlatList
   keyExtractor={this._keyExtractor}
   data={this.state.data}
   renderItem={this.renderItem}
   ItemSeparatorComponent={this.renderSeparator}
   extraData={this.state}
 />

你可以在小吃here参考

【讨论】:

  • 印刷机有变化,您能核实一下吗
  • 您的解决方案正在运行,但问题是我在 中的代码
  • 我没听懂你能不能详细点。
  • 我已经为 FlatList 使用了模拟数据并将其保存在一个单独的 tsx 文件中,并在我当前的类中导出 const PHARMACY 并将该 PHARMACY 分配给状态变量“数据”,在我的 FlatList 中我就位数据我只是调用 data={this.state.data} 这些是代码行 import PHARMACY from './api/mockPharmacyList'; this.state= {data: PHARMACY} ,
  • 我认为这没有任何问题,因为您正在向 flatlist 提供数据。你遇到了什么问题?
【解决方案2】:

首先,您需要像这样获取当前项目的索引:

const { item, index } = data;

获得当前项目的索引后,您可以检查当前单选按钮是否被选中,并且要更改单选按钮,您需要将当前索引的值传递给onPress 函数。

<RadioButton
  innerColor={Colors.darkBlue}
  outerColor={Colors.lightGray}
  animation={'bounceIn'}
  isSelected={this.state.selected === index}
  onPress={() => this.onPress(index)}
/>

【讨论】:

  • 选中了平面列表中的第一个单选按钮,但我无法选择其他单选按钮
  • 我将selectedIndexindex 进行比较,我将其更改为selected
  • 我在我的问题中附上了输出的截图,请检查一次
猜你喜欢
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
相关资源
最近更新 更多