programing

react Native에서 setNativePropes에 대한 useRef 후크를 사용하는 방법?

prostudy 2022. 3. 26. 16:44
반응형

react Native에서 setNativePropes에 대한 useRef 후크를 사용하는 방법?

React Native의 클래스 구성요소를 관련된 기능 구성요소로 변환하려고 함useRef. 클래스 구성 요소는 다음과 같다.

import React, { Component } from "react";
import { AppRegistry, StyleSheet, Text, View, Animated, TouchableWithoutFeedback } from "react-native";

import { interpolateNumber, interpolateRgb } from "d3-interpolate";

export default class animations extends Component {
  state = {
    animation: new Animated.Value(0)
  };

  componentWillMount() {
    const positionInterpolate = interpolateNumber(0, 200);
    const colorInterpolate = interpolateRgb("rgb(255,99,71)", "rgb(99,71,255)");;

    this.state.animation.addListener(({value}) => {
      const position = positionInterpolate(value);
      const color = colorInterpolate(value);

      const style = [
        styles.box,
        {
          backgroundColor: color,
          transform: [
            {translateY: position}
          ]
        }
      ];
      this._view.setNativeProps({ style });
    });
  }

  handlePress = () => {
    Animated.timing(this.state.animation, {
      toValue: 1,
      duration: 500,
    }).start();
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableWithoutFeedback onPress={this.handlePress}>
          <View style={styles.box} ref={view => this._view = view} />
        </TouchableWithoutFeedback>
      </View>
    );

  }
}

다음 기능 구성 요소로 변환할 때 다음 오류가 표시됨:

TypeRef.setNativeProps가 함수가 아닌 오류.('someRef.setNativeProps'({ style: style })에서 'someRef.setNativeProps'는 정의되지 않음)

import 
    React, 
    { 
        useState, 
        useEffect,
        useRef
    } from 'react'
import {
    View,
    Animated,
    TouchableWithoutFeedback,
    StyleSheet
} from 'react-native'
import {
    interpolateNumber,
    interpolateRgb, 
} from 'd3-interpolate'

export default d3number = () => {
    const [animation] = useState(new Animated.Value(1))
    const [position, setPosition] = useState()
    const someRef = useRef(null)
    const startAnimation = () => {
        Animated.timing(animation, {
            toValue: 2,
            duration: 1500,
        }).start()
    }

    const positionInterpolate = interpolateNumber(0, 300)
    useEffect(() => {
        animation.addListener(({value}) => {
            const pos = positionInterpolate(value)
            setPosition(pos)
        })
        const style = [
            styles.box, 
            {
                transform: [
                    {
                        translateY: position
                    }
                ]
            }
        ]
        someRef.setNativeProps({ style })
        // console.log(someRef.setNativeProps)
    }, [])

    return (
        <View style={styles.container}>
            <TouchableWithoutFeedback onPress={startAnimation}>
                <View 
                    style={styles.box}
                    ref={someRef}
                />
            </TouchableWithoutFeedback>
        </View>
    )
}

업데이트: 수신기 내에 스타일을 포함함으로써 해결됨

        if (!someRef.current) {
            return;
        }
        animation.addListener(({value}) => {
            const style = [
                styles.box, 
                {
                    transform: [
                        {
                            translateY: positionInterpolate(value)
                        }
                    ]
                }
            ]
            someRef.current.setNativeProps({ style })            
        })

        // console.log(someRef.setNativeProps)
    }, [someRef.current])

문서[1]에 따라 ref 값은 다음과 같이 유지된다.ref.current그러니까 넌 도망쳐야 해someRef.current.setNativeProps.

네 말이 맞았어.useEffect때문에 코드가 문제가 있을 것이다.someRef로 설정될 것이다null의 첫손에useEffect달리고 있다.덧붙여야 할 것이다.someRef.current에게useEffect종속성 배열로, 효과는 항상 호출됨someRef업데이트 및 호출되지 않는 조건 추가someRef.current.setNativeProps할 때someRef.current이다null. 전체를 건너뛰는 것이 좋을 것이다.useEffect하지 않는 한 몸.someRef.current아니다null.

    useEffect(() => {
        if (!someRef.current) {
          return;
        }
        animation.addListener(({value}) => {
            const pos = positionInterpolate(value)
            setPosition(pos)
        })
        const style = [
            styles.box, 
            {
                transform: [
                    {
                        translateY: position
                    }
                ]
            }
        ]
        someRef.current.setNativeProps({ style })
    }, [someRef.current]) # note the addition of `someRef.current` here so the effect runs again when the ref is set

[1] https://reactjs.org/docs/hooks-reference.html#useref

참조URL: https://stackoverflow.com/questions/57876152/how-to-use-the-useref-hook-for-setnativeprops-in-react-native

반응형