Как обрабатывать несколько флажков - PullRequest
1 голос
/ 02 октября 2019

Я работаю над проектом, в котором мне нужно отфильтровать результаты на основе проверенных позиций . Я хочу выбрать один или несколько элементов из разных категорий, а также consol.log (...) выбранных элементов, нажав кнопку Применить , чтобы узнать, какие элементы имеютбыл выбран. Вот скриншот экрана

enter image description here

Вот мой код

const{аллергены, кухня, доставка, диеты, окружающая среда, услуги} = this.state.data;

      <View style={styles.sliderContainer}>
        {allergens !== null && allergens !== undefined ? (
          <View>
            <Text style={styles.sliderLabel}>Allergens:</Text>
            {allergens.map((item, index) => {
              return (
                <View style={styles.checkBoxContainer} key={index}>
                  <Text style={{ fontSize: 16 }}>
                    {item && item[0]}{" "}
                    <Text style={{ fontSize: 16, color: "red" }}>
                      ({item && item[1]})
                    </Text>
                  </Text>
                  <CheckBox
                        checked={false}
                        onPress={() => this.handleValueChange()}
                  />
                </View>
              );
            })}
          </View>
        ) : null}
      </View>
<View style={styles.sliderContainer}>
            {environments !== null && environments !== undefined ? (
              <View>
                <Text style={styles.sliderLabel}>Environments:</Text>
                {environments.map((item, index) => {
                  return (
                    <View style={styles.checkBoxContainer} key={index}>
                      <Text style={{ fontSize: 16 }}>
                        {item && item[0]}{" "}
                        <Text style={{ fontSize: 16, color: "red" }}>
                          ({item && item[1]})
                        </Text>
                      </Text>
                      <CheckBox
                        checked={false}
                        onPress={() => this.handleValueChange()}
                      />
                    </View>
                  );
                })}
              </View>
            ) : null}
          </View>
          <View style={styles.sliderContainer}>
            {cuisine !== null && cuisine !== undefined ? (
              <View>
                <Text style={styles.sliderLabel}>Cuisine:</Text>
                {cuisine.map((item, index) => {
                  return (
                    <View style={styles.checkBoxContainer} key={index}>
                      <Text style={{ fontSize: 16 }}>
                        {item && item[0]}{" "}
                        <Text style={{ fontSize: 16, color: "red" }}>
                          ({item && item[1]})
                        </Text>
                      </Text>
                      <CheckBox
                        checked={false}
                        onPress={() => this.handleValueChange()}
                      />
                    </View>
                  );
                })}
              </View>
            ) : null}
          </View>

А вот данные , полученные из API

"cuisine": [
                    [
                        "Middle Eastern",
                        4
                    ],
                    [
                        "Western",
                        4
                    ],
                    [
                        "Pasta Dishes",
                        2
                    ],
                    [
                        "Salad",
                        2
                    ],
                    [
                        "Mexican",
                        1
                    ],
                    [
                        "Soup",
                        1
                    ],
                    [
                        "snacks",
                        1
                    ]
                ],
                "allergens": [
                    [
                        "Halal",
                        14
                    ]
                ],
                "environments": [
                    [
                        "Mexican",
                        15
                    ]
                ],

Как выбрать или отменить выбор элементов, не затрагивая других? Каково решение этой проблемы. Если этот подход не является хорошим, то какие будут альтернативы для выполнения этой задачи. Заранее спасибо.

Ответы [ 2 ]

1 голос
/ 02 октября 2019

Обновление: пример работы с React + JSX:

https://codesandbox.io/s/vigilant-snyder-kxh67

Вы можете попробовать этот способ:

<View style={styles.sliderContainer}>
        {allergens !== null && allergens !== undefined ? (
          <View>
            <Text style={styles.sliderLabel}>Allergens:</Text>
            {allergens.map((item, index) => {
              const key = `checkbox_${index}_value`;
              return (
                <View style={styles.checkBoxContainer} key={index}>
                  <Text style={{ fontSize: 16 }}>
                    {item && item[0]}{" "}
                    <Text style={{ fontSize: 16, color: "red" }}>
                      ({item && item[1]})
                    </Text>
                  </Text>
                  <CheckBox
                        onChange={() => this.handleValueChange(index)}
                        value={ this.state[key] || false }
                  />
                </View>
              );
            })}
          </View>
        ) : null}
      </View>
handleValueChange = (index) => {
   const key = `checkbox_${index}_value`;
   const newValue = !!!this.state[key];
   this.setState({
     [key]: newValue,
   }, () => {
     console.log('value changed: ', index, newValue);
   });

}

получить все значения:


getCheckboxes = () => {
  const values = this.state.data.allergens.map((v, index) => {
    const key = `checkbox_${index}_value`;
    const value = this.state[key] || false;
    return { index, value };
  });
  console.log('Checkboxes values: ', values);
}
0 голосов
/ 02 октября 2019

объявить состояние как this.state = {SelectedItem: []}

  1. Передать имя текущей кухни в "this.handleValueChange (item [0])"

  2. В функции this.handleValueChange (item),

Проверить, существует ли текущий элемент в this.state.selectedItem? Затем выскочить, если еще толкнуть его в массив. И сохранить состояние.

Console.log (this.state.selectedItem) при нажатии кнопки «Применить»

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...