我目前正在使用Modalize库实现模式。我正在为请求使用Hooks,但是一旦我要调用Modalize组件,它将返回以下错误。我花了很多时间,还没弄清楚问题出在哪里
import React, { useRef } from 'react';
import { Modalize } from 'react-native-modalize';
export default class MyScreen extends React.Component {
render() {
const modalizeRef = useRef(null);
function onOpen() {
modalizeRef.current?.open();
}
return (
<View>
<TouchableOpacity onPress={onOpen}>
<Text>click me</Text>
</TouchableOpacity>
<Modalize
ref={modalizeRef}
snapPoint={180}
>
<View
style={{
flex: 1,
height: 100,
flexDirection: 'row',
}}>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#29ae19' }]}>
Button 01
</TouchableOpacity>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#ff0000' }]}>
Button 02
</TouchableOpacity>
</View>
</Modalize>
</View>
);
}
}
答案 0 :(得分:1)
仅应在功能组件中使用挂钩。 阅读文档here
export default function MyScreen() {
const modalizeRef = useRef(null);
function onOpen() {
modalizeRef.current?.open();
}
return (
<View>
<TouchableOpacity onPress={onOpen}>
<Text>click me</Text>
</TouchableOpacity>
<Modalize
ref={modalizeRef}
snapPoint={180}
>
<View
style={{
flex: 1,
height: 100,
flexDirection: 'row',
}}>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#29ae19' }]}>
Button 01
</TouchableOpacity>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#ff0000' }]}>
Button 02
</TouchableOpacity>
</View>
</Modalize>
</View>
);
}
答案 1 :(得分:1)
根据我的收集,您需要推荐。 有两种方法
使用createRef在构造函数中声明它(无需导入)
constructor(props){
this.modalizeRef = React.createRef();
}
在组件调用中分配它
<Modalize
ref={(ref) => {
this.modalizeRef = ref;
}}
/>
答案 2 :(得分:0)
我设法通过使用refs callback
来解决此问题 export default class MyScreen extends React.Component {
constructor(props) {
super(props);
this.modalizeRef = React.createRef();
}
onOpen() {
this.modalizeRef.current?.open();
}
}
<View>
<TouchableOpacity onPress={this.onOpen.bind(this)}>
<Text>click me</Text>
</TouchableOpacity>
<Modalize
ref={this.modalizeRef}
snapPoint={180}
>
<View
style={{
flex: 1,
height: 100,
flexDirection: 'row',
}}>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#29ae19' }]}>
Button 01
</TouchableOpacity>
<TouchableOpacity style={[style.btnTest, { backgroundColor: '#ff0000' }]}>
Button 02
</TouchableOpacity>
</View>
</Modalize>
</View>