簡體   English   中英

如何在功能組件中使用 setNativeProps? React-native

[英]How do I use setNativeProps in Functional Components? React-native

我對 setNativeProps 究竟如何適用於功能組件感到困惑。 我的代碼適用於 class 組件,但我想將其全部更改為功能組件

所以我有我的功能組件:

export default function Item(props) {

在其中我有一個名為 onMoveX 的 function

    function onMoveX(dx) {
        refs['task'].setNativeProps({ style: { transform: [{ translateX: dx }] } });
    }

在我回來時,我有這個。

return (
        <View>
            
           <Animated.View ref='task' style={styles.item} {...panResponder.panHandlers}>
                <Text style={[styles.text, { flex: 1 }]}> {props.item.text} </Text>
            </Animated.View>

        </View>
    );

但是,我得到一個 Function Components cannot have ref 錯誤,我一直堅持如何解決這個問題。 我嘗試過 useState,但據很多人說它與 setNativeProps 相比效率低下。

在功能組件中,您可以通過以下方式使用“useRef”:

const taskRef = React.useRef();

function onMoveX(dx) {
    taskRef.current.setNativeProps({ style: { transform: [{ translateX: dx }] } });
}

return (
    <View>
        
       <Animated.View ref={taskRef} style={styles.item} {...panResponder.panHandlers}>
            <Text style={[styles.text, { flex: 1 }]}> {props.item.text} </Text>
        </Animated.View>

    </View>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM