我有两个组件,一个父功能组件和一个子类组件。我正在从父功能组件中的子类组件调用一个函数。以下是我尝试过的内容以及收到的错误消息。我想我遗漏了一些小东西,但不确定它是什么,希望得到任何帮助。
<块引用>TypeError: undefined is not an object (evaluating 'childRef.current.setModalOpen')
父功能组件:
import React, { useRef } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './screens/Home';
import Child from './screens/Child';
import Icon from 'react-native-vector-icons/AntDesign';
const Stack = createStackNavigator();
const App = () => {
const childRef = useRef();
handleShowModal = () => {
<Child ref={childRef}/>
childRef.current.setModalOpen();
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={Home} />
<Stack.Screen
name="Punt Repair Header"
component={Child}
options={{
headerRight: () => (
<Icon style={{ paddingLeft: 10 }}
name='plus'
size={30}
onPress={() => handleShowModal()}
/>
),
}}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default App;
子类组件:
import React from 'react';
import { View, Text, TextInput, StyleSheet, Modal } from 'react-native';
class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
}
render() {
setModalOpen = () => {
this.setState({ modalOpen:true });
}
return (
<View>
<Modal visible={this.state.modalOpen} animationType='slide'>
<View>
<Text>Model Content</Text>
</View>
</Modal>
</View>
);
}
}
答案 0 :(得分:0)
一般不能从父级调用子组件的方法,也不能直接从父级设置子组件的状态。
我认为您需要将 modalOpen
存储在父级的状态中(因此您需要将状态添加到父级 - 它不能是无状态的功能组件),然后将其作为道具向下传递给孩子。
所以 handleShowModal
变成了
handleShowModal = () => {
this.setState({showModal: true});
}
当你打电话给孩子时,它看起来像
<Icon style={{ paddingLeft: 10 }}
name='plus'
size={30}
onPress={() => handleShowModal()}
showModal={this.state.showModal}
/>
如果您希望两个组件都能够操作某些数据,那么它应该放在 Redux(或您使用的任何整体状态系统)中。