【问题标题】:Invalid use of hooks when calling component with onPress使用 onPress 调用组件时使用无效的钩子
【发布时间】:2019-12-27 15:03:24
【问题描述】:

当我单击标题中的按钮时,我正在尝试使用模式。

假设我有这个组件 List,而 List 正在使用自定义导航选项:

import { CustomModal } from './components/Modal';

const List = (props) => {
  const [enteredUrl, setEnteredUrl] = useState('');

  const urlInputHandler = (enteredUrl) => {
    setEnteredUrl(enteredUrl);
  };

  const addUrlHander = () => {
    console.log(enteredUrl);
  }

  return (
    <View></View>
  );
};

List.navigationOptions = (navData) => {
  return {
    headerTitle: 'Workouts',
    headerRight: (
      <HeaderButtons HeaderButtonComponent={HeaderButton}>
        <Item
          title='Add'
          iconName='md-add'
          onPress={() => {
            CustomModal(); //here is the modal
          }}
        />
      </HeaderButtons>
    ),
    headerBackTitle: null
  };
};

我的模态组件有这个:

export const CustomModal = (props) => {
  const [modalVisible, setModalVisible] = useState(false);
  console.log(props);
  return (
    <Modal
      animationType='slide'
      transparent={false}
      visible={modalVisible}
      onRequestClose={() => {
        Alert.alert('Modal has been closed.');
      }}
    >
      <View style={{ marginTop: 22 }}>
        <View>
          <Text>Hello World!</Text>

          <TouchableHighlight
            onPress={() => {
              setModalVisible(!modalVisible);
            }}
          >
            <Text>Hide Modal</Text>
          </TouchableHighlight>
        </View>
      </View>
    </Modal>
  );
}

但它给了我无效的钩子错误。为什么我的导航选项中的 onPress 给了我这个?我做错了吗?

【问题讨论】:

  • 但是您导出的是 CustomModal 而不是 Modal ?
  • 哎呀,当我写这个问题时,它是在我的脑海中,但实际上我做对了

标签: reactjs react-native react-hooks reactjs-native


【解决方案1】:

onPress 是回调,不能在里面放组件。可能你想要的是这样的:

      <HeaderButtons HeaderButtonComponent={HeaderButton}>
        <CustomModal/>
      </HeaderButtons>

模态看起来像

export const CustomModal = (props) => {
  const [modalVisible, setModalVisible] = useState(false);
  console.log(props);
  return modalVisible?(
    <Modal
      animationType='slide'
      transparent={false}
      visible={modalVisible}
      onRequestClose={() => {
        Alert.alert('Modal has been closed.');
      }}
    >
      <View style={{ marginTop: 22 }}>
        <View>
          <Text>Hello World!</Text>

          <TouchableHighlight
            onPress={() => {
              setModalVisible(!modalVisible);
            }}
          >
            <Text>Hide Modal</Text>
          </TouchableHighlight>
        </View>
      </View>
    </Modal>
  ):(
    <Item
      title='Add'
      iconName='md-add'
      onPress={() => setModalVisible(!modalVisible)}
    />
  );
}

【讨论】:

  • 谢谢,这帮助了我。但是,这给了我一个错误,因为 HeaderButtons 是需要 组件的第 3 方组件。所以我不得不将 组件也放入 CustomModal 组件中。
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 2021-11-03
  • 2021-07-08
  • 2022-07-14
  • 2020-11-29
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多