Как изменить представление для отдельного списка в React Native?

Я хочу изменить вид кнопки «Подписаться», чтобы отменить подписку при нажатии определенной кнопки просмотра списка. В настоящее время, когда я нажимаю любую кнопку подписки, каждая кнопка подписки в списке меняется на отмену подписки. я просто хочу изменить конкретную кнопку подписки в списке?

Изображение кнопки подписки

/** * Пример приложения React Native * https://github.com/facebook/react-native * @поток */

import React, { Component } from 'react';
import{Platform,StyleSheet,Text,View,Image,ListView,TouchableOpacity,ImageBackground,TouchableHighlight
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import ActionButton from 'react-native-action-button';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { TabNavigator, StackNavigator } from 'react-navigation';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { Container, Header, Content, Card, CardItem, Thumbnail, Button, Left, Body, Right } from 'native-base';
const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class Followers extends Component{
  static navigationOptions = { 
      headerTitle: 'Followers',      
      headerTitleStyle: {
          color: '#36292a',
          fontFamily: 'WorkSans-Regular',
          fontWeight: '300',
          marginLeft: 0
          },
        };

  constructor(props) {
    super(props);
    this.state = {
      follow: true,
    };
  }

  updateSearchStatus = () => 
    this.setState({ 
      follow : this.state.follow,
  });

    updateTitleStatus = () =>
    this.setState({
    } , () => {
      //this.ButtonState();
      if(this.state.follow == true){
        this.setState({
          follow : false
        });
      }else{
        this.setState({
          follow : true
        });
      }      
  });



displayImages(users){
    var {navigate} = this.props.navigation;
    return(  
    <View style={styles.container}>       
            <CardItem style={{height: 78,borderBottomWidth:1,borderColor: '#dadddf'}}>
              <Left>
                <Thumbnail source={{uri: users.avatar_url}} style={{height: 40, width: 40}} />
                <Body>
                  <Text style={styles.uploaderName}>{users.name}</Text>
                </Body>
              </Left>
              <Right>
                <TouchableHighlight underlayColor = '#DFE1E3' onPress={this.updateTitleStatus} >
                  { this.state.follow ? <View style={styles.followouter}><Text style={{color:'#fefefe',fontSize: 12}}>Follow</Text></View> 

                       : <View style={styles.unfollowouter}><Text style={{color:'#36292a',fontSize: 12}}>Unfollow</Text></View> 

                    }
                </TouchableHighlight>
              </Right>
            </CardItem>
       </View>      
    );
  }

  render() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    var {navigate} = this.props.navigation;
    var users = [
      {
        name: 'Amy Farha',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
        image: 'https://i.pinimg.com/564x/1c/f3/05/1cf305362aed02ad559f989687b1460e.jpg',
      },
      {
        name: 'Chris Jackson',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
        image: 'https://i.pinimg.com/236x/a8/37/8e/a8378eeb01ec788a0068ea6b1b759091.jpg',
      },
      {
        name: 'Amanda Martin',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
        image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
      },
      {
        name: 'Amy Farha',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
        image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
      },
      {
        name: 'Chris Jackson',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
        image: 'https://i.pinimg.com/564x/66/f0/2f/66f02f37eb54ff7f79f4c831212b231f.jpg',
      },
      {
        name: 'Amanda Martin',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
        image: 'https://i.pinimg.com/564x/58/0c/78/580c789ded6ceeafdf71b792b0d57ac6.jpg',
      },
      {
        name: 'Amy Farha',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
        image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
      },
      {
        name: 'Chris Jackson',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
        image: 'https://i.pinimg.com/564x/47/6b/5c/476b5c4c9725ff3cd4bb3e5f61e4d6c3.jpg',
      },
      {
        name: 'Amanda Martin',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
        image: 'https://i.pinimg.com/564x/ad/4b/06/ad4b06523eefacc30d09d41a9992029f.jpg',
      },
      {
        name: 'Christy Thomas',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
        image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
      },
      {
        name: 'Melissa Jones',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
        image: 'https://i.pinimg.com/564x/82/ac/2e/82ac2e1c86692090173666496b9ce1cf.jpg',
      },
      {
        name: 'Amanda Martin',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg',
        image: 'https://i.pinimg.com/564x/8a/db/a7/8adba7207bdc82668bf06acc2734537e.jpg',
      },
      {
        name: 'Christy Thomas',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
        image: 'https://i.pinimg.com/564x/a5/4d/4d/a54d4d37522a76a67002fa25b8e51515.jpg',
      },
      {
        name: 'Melissa Jones',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
        image: 'https://i.pinimg.com/564x/ae/b6/ac/aeb6ac2f05644f1464c298bf979630e9.jpg',
      },
      {
        name: 'Christy Thomas',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/kfriedson/128.jpg',
        image: 'https://i.pinimg.com/564x/57/ac/3e/57ac3e724c61f9b9803d520574e42a1e.jpg',
      },
      {
        name: 'Melissa Jones',
        avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg',
        image: 'https://i.pinimg.com/564x/66/f0/2f/66f02f37eb54ff7f79f4c831212b231f.jpg',
      },
    ];

    var cloneUsers = ds.cloneWithRows(users);

    return (  
    <View style={{flex: 1}}>    
        <ListView
          style={styles.listView}
          dataSource={cloneUsers}
          renderRow={this.displayImages.bind(this)}
          renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
        />     
        </View>

    );  
  }
}

const styles = StyleSheet.create({
  icon: {
    width: 26,
    height: 26,
  },
  container: {
    flex: 1,
    backgroundColor: '#fefefe'
  },
  uploaderName:{
    fontSize: 16,
    color: '#36292a'
  },
  actionButtonIcon: {
    color: '#fefefe',  
  },
  followouter: {
      justifyContent: 'center',
      alignItems: 'center',
      width: 90, 
      height: 25, 
      borderRadius: 4,  
      backgroundColor: '#f00039'
    },
  unfollowouter: {
    justifyContent: 'center',
      alignItems: 'center',
      width: 90, 
      height: 25, 
      borderRadius: 4, 
      borderWidth:1, 
      borderColor: '#999296',
  }

});

person Kamlesh Tilwani    schedule 23.01.2018    source источник
comment
Вы пытались использовать переключаемую привязку?   -  person mast3rd3mon    schedule 23.01.2018
comment
Это должно указать вам правильное направление: stackoverflow.com/questions/48326655/   -  person MattyK14    schedule 23.01.2018


Ответы (3)


Все кнопки переключаются на отмену подписки, потому что вы используете одно и то же состояние this.state.follow для всех кнопок. Поэтому, когда он становится ложным, все кнопки будут отображать отмену подписки.

Что вы можете сделать, так это добавить атрибут follow в свой пользовательский объект, и вместо тестирования this.state.follow ?... вы можете сделать user.follow ?....

И в вашей функции updateSearchStatus() вы можете передать пользователю возможность найти его и изменить его followstatus.

person Community    schedule 23.01.2018
comment
Я не получил от тебя ответа. Я новичок в этом. Не могли бы вы помочь мне с этим вкратце? ТИА - person Kamlesh Tilwani; 23.01.2018

Вот вам пример:

Создать состояние для магазина, которое нажато/выбрано

this.state = { selected: null };

Передайте индекс элемента, который нажат/выбран

updateSearchStatus = (index) => this.setState({ selected : index });

Ваш renderItem должен иметь какое-то условие для кнопки элемента.

<View style={ this.state.selected == item.index ? styles.followouter : styles.unfollowouter}>
    <Text style={{color:'#fefefe',fontSize: 12}}>
        {this.state.selected == item.index ? 'Follow' : 'Unfollow'}
    </Text>
</View> 

Надеюсь, это поможет вам для идеи

person Seyha    schedule 23.01.2018
comment
Привет, @KamleshTilwani, элемент относится к пользователю или каждой строке или user.id или user.index - person Seyha; 24.01.2018

Есть много решений этой проблемы, но мое предложение таково. В папке проекта создайте папку с именем components. Внутри этой папки создайте файл с именем Toggle.js. Внутри этого файла используйте этот код.

    export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSelected: false,
      follow: true,
    }
  }
  updateTitleStatus = () =>
    this.setState({}, () => {
      if (this.state.follow == true) {
        this.setState({
          follow: false
        });
      } else {
        this.setState({
          follow: true
        });
      }
    });
  render() {
    return (
      <TouchableHighlight underlayColor='#DFE1E3' onPress={this.updateTitleStatus} >
        {this.state.follow ? <View style={styles.followouter}><Text style={{ color: '#fefefe', fontSize: 12 }}>Follow</Text></View>
          : <View style={styles.unfollowouter}><Text style={{ color: '#36292a', fontSize: 12 }}>Unfollow</Text></View>}
      </TouchableHighlight>
    );
  }
}
const styles = StyleSheet.create({
  followouter: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 90,
    height: 25,
    borderRadius: 4,
    backgroundColor: 'dodgerblue'
  },
  unfollowouter: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 90,
    height: 25,
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#999296',
  }
});

А затем внесите это изменение в свой текущий файл.

    //.....
import Toogle from '../components/Toogle';
''''''
...
displayImages(users){
    var {navigate} = this.props.navigation;
    return(  
    <View style={styles.container}>       
            <CardItem style={{height: 78,borderBottomWidth:1,borderColor: '#dadddf'}}>
              <Left>
                <Thumbnail source={{uri: users.avatar_url}} style={{height: 40, width: 40}} />
                <Body>
                  <Text style={styles.uploaderName}>{users.name}</Text>
                </Body>
              </Left>
              <Right>
                <Toogle/>
              </Right>
            </CardItem>
       </View>      
    );
  }
......
....//

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

person Staniya Figarado    schedule 06.03.2020