0

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

假设我有这个组件列表,并且列表正在使用自定义导航选项:

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 给了我这个?我做错了吗?

4

1 回答 1

0

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)}
    />
  );
}
于 2019-12-27T15:23:27.110 回答