Как добавить операторы If для выпадающего меню React Native - PullRequest
0 голосов
/ 23 марта 2020

Я новичок в React и не могу понять, как добавить оператор if, который будет проверять, какой элемент выпадающего меню был выбран при нажатии кнопки.

Я в основном хочу if (button was pressed && input is valid) { print a random song in a list of songs in that genre } Как я бы go об этом? В настоящее время у меня есть выпадающее меню с идентификатором, именем и песнями. items.songs - это список из 3-4 песен, я планирую добавить больше песен в будущем, но я хочу, чтобы приложение работало до этого.

Мой код в настоящее время выглядит следующим образом. В той части, где есть комментарии псевдокодов операторов if, я думаю, что операторы if должны go, но, как я уже говорил, я новичок в React, поэтому, пожалуйста, дайте мне знать, как решить эту проблему!

import React, { Component, Fragment } from 'react';
import { StyleSheet, Text, TextInput, View, Button, Alert } from 'react-native';
import SearchableDropdown from 'react-native-searchable-dropdown';

var items =[
    {
      id: 1,
      name: 'Happy',
      songs: ['best day ever', 'kool aid & frozen pizza', 'nikes on my feet']
    },
    {
      id: 2,
      name: 'Sad',
      songs: ['self care', 'ROS', 'stay', 'whats the use']
    },
    {
      id: 3,
      name: 'Chill',
      songs: ['good news', 'clymation', 'the star room']
    },
    {
      id: 4,
      name: 'Hype',
      songs: ['donald trump', 'remember', 'weekend']
    }
];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: []
    }
  }
  render() { 
    // If items.id = 1, print a random song from the list of happy songs
    // If items.id = 2, print a random song from the list of sad songs
    // etc.

    return (
      <Fragment>
          <SearchableDropdown
            onItemSelect={(item) => {
              const items = this.state.selectedItems;
              items.push(item)
              this.setState({ selectedItems: items
              });
            }}
            containerStyle={{ padding: 5 }}
            onRemoveItem={(item, index) => {
              const items = this.state.selectedItems.filter((sitem) => sitem.id !== item.id);
              this.setState({ selectedItems: items });
            }}
            itemStyle={{
              padding: 10,
              marginTop: 2,
              backgroundColor: '#ddd',
              borderColor: '#bbb',
              borderWidth: 1,
              borderRadius: 5,
            }}
            itemTextStyle={{ color: '#222' }}
            itemsContainerStyle={{ maxHeight: 140 }}
            items={items}
            defaultIndex={2}
            resetValue={false}
            textInputProps={
              {
                placeholder: "What kind of music do you want to hear?",
                underlineColorAndroid: "transparent",
                style: {
                    padding: 12,
                    borderWidth: 1,
                    borderColor: '#ccc',
                    borderRadius: 5,
                },
              }
            }
            listProps={
              {
                nestedScrollEnabled: true,
              }
            }
        />
      <View style={ styles.button }>
        <Button
          title="Press me for a song to match your mood!"
          onPress={() => 
            console.log('Simple Button pressed')

          }
        />
      </View>
      </Fragment> 
    );
  }
}

const styles = StyleSheet.create({
  button: {
    padding: 25,
    alignSelf: 'center',
  }
});
...