반응형
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
반응형
'programing' 카테고리의 다른 글
react-router에서 앱의 기본 이름 구성 (0) | 2022.03.26 |
---|---|
대용량 데이터에 대한 Vue 2 메모리 사용 처리 방법(약 50,000개의 개체) (0) | 2022.03.26 |
vue.js 2에서 개체 관찰자를 루핑하려면 어떻게 해야 하는가? (0) | 2022.03.26 |
Vuetify에서 v-img에서 폴백을 어떻게 하는가? (0) | 2022.03.26 |
소품에서 구성 요소 초기화 상태 반응 (0) | 2022.03.26 |