首页 > 解决方案 > 检测是否没有选中复选框 React Native

问题描述

Checkboxes我在 React Native 中制作了自己的组件。I want to have a functionality so that if no checkboxes are selected, then a button is disabled , but when there is one or more selected, it is enabled . 这是我的复选框组件:

const CheckboxList = (props) => {
  const renderItem = ({ item }) => (
    <CheckboxRow title={item.title} checked={item.checked} />
  );
  return (
    <FlatList
      data={props.data}
      renderItem={renderItem}
      keyExtractor={item => item.id}
      style={styles.flatList}
      ItemSeparatorComponent={FlatListDivider}
      scrollEnabled={false}
    />
  );
};

更新:这里是 CheckboxList 组件和按钮的连接方式:

<CheckboxList
  data={DATA}
/>

<TouchableOpacity
  onPress={() => {
    navigation.navigate('Screen3');
  }}
  style={styles.button}
  disabled={false}> // make this true if none are selected
  <Text style={styles.buttonText}>
    Continue
  </Text>
</TouchableOpacity>

如上所示,它们都在同一个渲染中。

更新:这是我更新选中与未选中的方式:

const RadioRow = (props) => {
  const [checked, setChecked] = useState(props.checked)
  return (
    <TouchableOpacity onPress={() => setChecked(!checked)}>
      <View style={styles.container}>
        <MaterialCommunityIcons size={40} name={checked ? 'check-circle' : 'checkbox-blank-circle-outline'} color={blue} />
        <Text style={styles.title}>{props.title}</Text>
      </View>
    </TouchableOpacity>
  );
};

标签: reactjsreact-native

解决方案


如果在检查项目时您的 DATA 数组正在更新,您可以简单地执行以下操作。When the selected count is 0 it will disable the touchableopacity

假设您将 DATA 保持在状态

<TouchableOpacity
  onPress={() => {
    navigation.navigate('Screen3');
  }}
  style={styles.button}
  disabled={DATA.filter(item => item.checked).length === 0}> // make this true if none are selected
  <Text style={styles.buttonText}>
    Continue
  </Text>
</TouchableOpacity>
<CheckboxList
  data={DATA}
  onChange={onChange}
/>

您将需要一个 Onchange 函数来从子元素更新它

onChange=(id)=>{
  const updatedData=[...DATA];
  const item=updatedData.find(x=>x.id===id);
  item.checked=!item.checked;
  setData(updatedData);
}

其他组件会将其作为道具并更新父状态

const CheckboxList = (props) => {
  const renderItem = ({ item }) => (
    <RadioRow id={item.id} title={item.title} checked={item.checked} onChange={props.onChange}/>
  );
  return (
    <FlatList
      data={props.data}
      renderItem={renderItem}
      keyExtractor={item => item.id}
      style={styles.flatList}
      ItemSeparatorComponent={FlatListDivider}
      scrollEnabled={false}
    />
  );
};

const RadioRow = (props) => {

  return (
    <TouchableOpacity onPress={() => props.onChange(item.id}>
      <View style={styles.container}>
        <MaterialCommunityIcons size={40} name={checked ? 'check-circle' : 'checkbox-blank-circle-outline'} color={blue} />
        <Text style={styles.title}>{props.title}</Text>
      </View>
    </TouchableOpacity>
  );
};

推荐阅读