Как я могу изменить текст состояния с помощью React Native?

По сути, я делаю приложение, в котором вы проводите пальцем вправо, если хотите, и влево, если нет. Проблема, с которой я столкнулся сейчас, заключается в том, что я хочу, чтобы на карточке отображался правильный текст, который меняется в зависимости от направления, в котором пользователь проводит пальцем.

PanResponder обрабатывает изменяемый текст путем модификации state.changeText и изменяет текст в зависимости от направления. Код частично работает в настоящий момент, но проблема, с которой я столкнулся сейчас, заключается в том, что предыдущее значение состояния для changeText - это то, что отображается во время процесса считывания, а не текущее.

Код показан ниже.

import React from "react"
import {
  View, Text, Animated, ScrollView, StyleSheet, Button,PanResponder,Dimensions
} from "react-native"
import Icon from "react-native-vector-icons/Ionicons" 
import {Card, Badge} from "react-native-elements"

const screenWidth =Dimensions.get("window").width
const swipeThreshold = screenWidth * .25


export default class SwipeCard extends React.Component{
  constructor(props){
    super(props);
    //this initiates the dragging animation
    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      // if true anytime the user starts to click down on the screen, the panresponder handles the action

        onStartShouldSetPanResponder : () => true,
          //everytime the user drags on the screen
        onPanResponderMove : (event, gesture) => {
          //get the distance they dragged the item by and update it in the animation
          position.setValue({x: gesture.dx, y: gesture.dy})
          this.setState({
            style:{
              opacity:1,
          }})

        },
        //everytime the user lets go
        onPanResponderRelease: (event, gesture) => {
          this.setState({
            style:{
              opacity:0,
          }})
          if (gesture.dx > swipeThreshold){
            console.info("swipe right!");
            this.setState({change: "swipe right!"})
            position.setValue({x:0, y:0});

            this.nextItem();
          }
          else if (gesture.dx < -swipeThreshold){
            console.info("swipe left!");
            this.changeText("swipe left")
            this.setState({change: "swipe left!"})

            position.setValue({x:0, y:0});

            this.nextItem();
          }
          else{
            position.setValue({x:0, y:0});
            this.setState({
              style:{
                opacity:0,
            }})
          }
        }
    })
    this.state = {
      index:1,
      panResponder,
      position,
      style:{
        opacity:0,
      },
      changeText:"",
    }
    this.nextItem=this.nextItem.bind(this);
  }


  getCardStlye(){
    const {position} = this.state;
    const rotate = position.x.interpolate({
        inputRange: [-screenWidth * 2, 0, screenWidth*2],
        outputRange: ["-120deg", "0deg", "120deg"]
    });
    return {
      ...position.getLayout(),
      transform: [{rotate}]

    }
  }



  nextItem() {
        if (this.state.index !== this.props.data.length){
           this.setState({ index: this.state.index + 1 })
       }
       else {
          this.setState({ index:0});
        }

  }
  render(){
    var cloth = this.props.data.find((cloth, i)=>{
      return i+1 === this.state.index;
    })

    return(
        <ScrollView>
           {this.state.index ?(
        <Animated.View
           key  = {cloth.deal.id}
           style = {this.getCardStlye()}
           {...this.state.panResponder.panHandlers}>
           <Card
             title = {cloth.deal.merchant.name}
             image  = {{uri:cloth.deal.image_url}}
             >
             <Text
                style  = {this.state.style}>
                {this.state.changeText}
                </Text>
             <Text>${cloth.deal.price}</Text>
             <Button
               title = "Details"
               backgroundColor = "blue"
             ></Button>
             </Card>
         </Animated.View>
           )
         :
         <Text>Null</Text>
           }
       </ScrollView>
    )
 }


  }

Вы устанавливаете состояние с помощью this.setState ({изменение: "проведите пальцем влево!"}) И используете this.state.changeText

Kranthi 10.10.2018 11:17
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
1
379
2

Ответы 2

По-видимому, у вас есть ошибка, у вас нет метода изменения текста в вашем классе, но вы используете его для прокрутки влево, попробуйте удалить его и проверьте, работает ли он

      if (gesture.dx > swipeThreshold){
        console.info("swipe right!");
        this.setState({change: "swipe right!"})
        position.setValue({x:0, y:0});

        this.nextItem();
      }
      else if (gesture.dx < -swipeThreshold){
        console.info("swipe left!");
        this.changeText("swipe left") // <<< HERE
        this.setState({change: "swipe left!"})

        position.setValue({x:0, y:0});

        this.nextItem();
      }
      else{

Собственно я осознал свою ошибку. Добавление setState в onPanResponderMove помогло

const panResponder = PanResponder.create({
  // if true anytime the user starts to click down on the screen, the panresponder handles the action

    onStartShouldSetPanResponder : () => true,
      //everytime the user drags on the screen
    onPanResponderMove : (event, gesture) => {
      //get the distance they dragged the item by and update it in the animation
      position.setValue({x: gesture.dx, y: gesture.dy})
      if (gesture.dx > swipeThreshold){
        console.info("swipe right!");
        this.setState({changeText: "swipe right!"})
      }
      else if (gesture.dx < -swipeThreshold){
        console.info("swipe left!");
        this.setState({changeText: "swipe left!"})
      }
      else{
        this.setState({
          style:{
            opacity:0,
        }})
      }
      this.setState({
        style:{
          opacity:1,
      }
    })

    },
    //everytime the user lets go
    onPanResponderRelease: (event, gesture) => {
      this.setState({
        style:{
          opacity:0,
      }})
      if (gesture.dx > swipeThreshold){
        console.info("swipe right!");
        this.setState({changeText: ""})
        position.setValue({x:0, y:0});
        this.addItems()
        this.nextItem();
      }
      else if (gesture.dx < -swipeThreshold){
        console.info("swipe left!");
        this.setState({changeText: ""})
        position.setValue({x:0, y:0});
        this.nextItem();
      }
      else{
        position.setValue({x:0, y:0});
        this.setState({
          style:{
            opacity:0,
        }})
      }
    }
})
this.state = {
  index:1,
  panResponder,
  position,
  style:{
    opacity:0,
  },
  changeText:"",
  items:[],
  itemName:"",
}

Другие вопросы по теме