在项目组中使用 React Native 状态管理所选项目样式

我正在更新我的饮水提醒应用程序,用户可以在其中选择一种类型的饮料然后喝水。


我想要做的是我有一个包含饮料的数组,并通过该数组映射以显示它们。我需要用户选择哪种饮料,她想喝。选择后,我想更改其样式以突出显示所选饮料。


我已经尝试过带有 selectedDrink 状态的嵌套对象,但据我在这里读到,嵌套对象在 React 中的性能不佳。


当我使用选定状态并单击其中任何一个时,所有样式都会更改。


state = {

    selected: false

    selectedDrink: {

        Water: false,

        Coffee: true,

        Tea: false,

    },

};


drinkList = (begin, end) => {


    drinks = [

      'Water',

      'Coffee',

      'Tea',

    ];

    drinks = drinks.slice(begin, end);


return drinks.map(data => {

  const imageLinks = {

    Water: require('../assets/images/Water.png'),

    Coffee: require('../assets/images/Coffee.png'),

    Tea: require('../assets/images/Tea.png'),

  };


  {

    if (data === 'Water') {

      image = <Image style={styles.drinkImages} source={imageLinks.Water} />;

    } else if (data === 'Coffee') {

      image = <Image style={styles.drinkImages} source={imageLinks.Coffee} />;

    } else if (data === 'Tea') {

      image = <Image style={styles.drinkImages} source={imageLinks.Tea} />;

    } else {

      image = <Image style={styles.drinkImages} source={imageLinks.Water} />;

    }

  }


  return (

    <View style={styles.drinkContainer}>

      <TouchableOpacity

        onPress={() => {

          this.setState({ selected: !this.state.selected });

        }}


        //this is where I would like to change style based on state

        style={[

          styles.drinkButtonContainer,

          this.state.selected ? styles.drinkSelectedButtonContainer : null,

        ]}

      >

        {image}

      </TouchableOpacity>

      <Text style={styles.infoTextStyle}>{data}</Text>

    </View>

  );

});

};


青春有我
浏览 154回答 1
1回答

临摹微笑

我所做的是用空字符串创建选定状态。每次单击该项目的任何人时,我都会使用饮料名称设置状态,然后将所选状态与饮料名称进行比较,如果匹配样式将应用于所选饮料state = {&nbsp; selected: '',};&nbsp; return (&nbsp; &nbsp; <View style={styles.drinkContainer}>&nbsp; &nbsp; &nbsp; &nbsp; // I set the state to drink name&nbsp; &nbsp; &nbsp; <TouchableOpacity&nbsp; &nbsp; &nbsp; &nbsp; onPress={() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({ selected: data });&nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; // Then compare drink name with selected state and apply styling&nbsp; &nbsp; &nbsp; &nbsp; style={[&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; styles.drinkButtonContainer,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.selected === data ? styles.drinkSelectedButtonContainer : null,&nbsp; &nbsp; &nbsp; &nbsp; ]}&nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; {image}&nbsp; &nbsp; &nbsp; </TouchableOpacity>&nbsp; &nbsp; &nbsp; <Text style={styles.infoTextStyle}>{data}</Text>&nbsp; &nbsp; </View>&nbsp; );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript