首页 > 解决方案 > 在 react-native 的 navigationOptions 中使用上下文

问题描述

我正在尝试在 Component.navigationOptions 中使用我创建的上下文,但我无法从组件外部访问它

我已经尝试过“props.navigation.setParams/props.navigation.getParams”,但它们总是冻结我的屏幕并且它们没有任何好处

const AddNoteScreen = props => {
    const {addNote} = useContext(Context);
    const [title, newTitle] = useState('');
    const [description, newDescription] = useState('');

    props.navigation.setParams(addNote);


    return <>
        <Spacer/>
        <Input label='Note Title' value={title} onChangeText={newTitle} />
        <Spacer/>
        <Spacer/>
        <Input label='Note Detail' value={description} onChangeText={newDescription} multiline={true} numberOfLines={9} />
    </>
}

AddNoteScreen.navigationOptions = ({navigation}) => {
    return {
        title: "Add your note",
        headerTintColor: navigation.getParam('HeaderTintColor', '#fff'),
        headerStyle: {
            backgroundColor: 'rgb(254, 56, 56)',
            borderBottomEndRadius : 18,
            borderBottomStartRadius : 18,
        },
        headerRight: (
            <TouchableOpacity onPress={() => 
             navigation.getParam(addNote(newTitle, newDescription))}>
                <Feather style={styles.plus} name="plus" size={25}/>
            </TouchableOpacity>
        ),
    }
};

我希望能够像这样在 navigationOptions 中使用上下文,但就像我说的那样,发生了一些奇怪的事情并且没有任何效果。

标签: reactjsreact-nativereact-native-androidreact-native-ios

解决方案


要访问addNote()静态 navOptions 内部,您应该像这样调用它:navigation.state.params.addNote()并将 AddNoteScreen 的状态留在 navOptions 之外。

const AddNoteScreen = props => {
  const { addNote } = useContext(Context);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const callNoteFromNav = () => {
    addNote(newTitle, newDescription);
  };

  props.navigation.setParams(callNoteFromNav);

  return (
    <>
      <Spacer />
      <Input label="Note Title" value={title} onChangeText={setTitle} />
      <Spacer />
      <Spacer />
      <Input
        label="Note Detail"
        value={description}
        onChangeText={setDescription}
        multiline={true}
        numberOfLines={9}
      />
    </>
  );
};

AddNoteScreen.navigationOptions = ({ navigation }) => {
  return {
    title: 'Add your note',
    headerTintColor: navigation.getParam('HeaderTintColor', '#fff'),
    headerStyle: {
      backgroundColor: 'rgb(254, 56, 56)',
      borderBottomEndRadius: 18,
      borderBottomStartRadius: 18
    },
    headerRight: (
      <TouchableOpacity
        onPress={() => navigation.state.params.callNoteFromNav()}
      >
        <Feather style={styles.plus} name="plus" size={25} />
      </TouchableOpacity>
    )
  };
};

您不应该尝试访问 navOptions 中的状态,因为它是静态的。但是,这将是未来版本的一个功能。我可以建议您查看React Navigation Next。React Navigation 的人用一种更 React 的方式来配置header替换了静态选项。

快乐编码!


推荐阅读