[英]How to do a this with a component in react native?
我正在使用 react native 和 expo.cli 并且想知道如何设法将句柄添加到 TouchableOpacity,我有以下组件:
function MainModal (){
return(
<>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
onPress={this.TouchableOpacity}
>
<Text>Volver</Text>
</TouchableOpacity>
</View>
</>
我想要做的是在选择这个特定的TouchableOpacity时引用它,但是当我使用嵌套在组件中的“this”时,我收到以下错误:未定义不是对象(评估'this.TouchableOpacity')我也许知道这个问题有点新手,与“this”在javascript中的工作方式有关,而不是与React Native本身有关,但是我找不到一种方法来引用所选对象以便它执行某些东西选择时。 我怎么能做到?
您可以使用React.useRef()
挂钩来创建对该元素的引用,以便您可以访问它。 你对this
的想法不是实际的this
。 This
可能指的是全局对象(不严格),并且在严格模式下可能未定义。 如果您想在组件中使用this
,我建议您创建一个class
组件而不是函数组件。 在 MDN 中查看此内容以了解更多信息。 无论如何,在功能组件中使用 ref 将是这样的:
function MainModal (){
const touchableReference = React.useRef()
const handleTouchableClick = () => {
console.log(touchableReference.current)
//
// Outputs HTMLDivElement...
//
}
return(
<>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
ref={touchableReference}
onPress={() => handleTouchableClick()}
>
<Text>Volver</Text>
</TouchableOpacity>
</View>
</>
)
}
在功能组件中传递事件处理程序的一种标准方法如下
function MainModal (props){
const onPress1 = useCallback(()=>console.log); // created inside the componet
const {onPress2} = props; // passed from props
const {onPress3} = useSomeHook(); // from context/hook
return(
<>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
onPress={onPress1}
>
<Text>Volver</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={onPress2}
>
<Text>Volver</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={onPress3}
>
<Text>Volver</Text>
</TouchableOpacity>
</View>
</>
);
}
this
行为在 react 和 react-native 中是一样的。 React 功能组件在渲染阶段执行,你不应该在this
使用它,因为你不知道它何时何地被调用。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.