只允许在React Native FlatList中选择一项

时间:2019-12-18 18:59:27

标签: javascript reactjs react-native

我当前正在设计一个应用程序,该应用程序要求从给定列表中选择一位老师。但是,我目前对如何仅允许用户从给定的FlatList中选择一个项目感到困惑,并且如果用户在列表中选择了另一个项目,它将取消选择先前的选择。该应用程序使用React-Native的FlatList组件,关注的主要功能是TeacherList组件,我真的很感激任何解决方案!


function ListTeacher( {id, name, selected, onSelect} ) {
  return (
    <View style={styles.item}>
      <TouchableOpacity
      style={styles.teacherName}
      onPress={() => onSelect(id)}
      >
        <Text style={[styles.teacherName, { color: selected ? '#44B0F2' : (theme == 'dark' ? 'white' : 'black') }]}> {name} </Text>
      </TouchableOpacity>
    </View>
  );
}


const TeacherList = (props) => {
  const [selected, setSelected] = React.useState(new Map());

  const onSelect = React.useCallback(
    id => {
      const newSelected = new Map(selected);

      newSelected.set(id, !selected.get(id));

      setSelected(newSelected);
    },
    [selected],
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={teachers}
        keyboardShouldPersistTaps={'handled'}
        renderItem={({ item }) => (
          <ListTeacher
            id={item.id}
            name={item.name}
            selected={!!selected.get(item.id)}
            onSelect={onSelect}
          />
        )}
        keyExtractor={item => item.id}
        extraData={selected}
      />
    </View>
  );
}```

1 个答案:

答案 0 :(得分:0)

在这种情况下,您不需要new Map(),您只想将用户选择存储在变量中。例如

const [selected, setSelected] = React.useState(null);
const onSelect = (id) => {
 setSelected(id);
}
<ListTeacher
        id={item.id}
        name={item.name}
        selected={item.id === selected}
        onSelect={onSelect}
 />