reactjs - 在 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 中使用上下文,但就像我说的那样,发生了一些奇怪的事情并且没有任何效果。
解决方案
要访问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替换了静态选项。
快乐编码!
推荐阅读
- algorithm - 用单因素或多因素求解算法抛硬币?
- json - 如何在android中将jsonarray转换为jsonobject
- c++ - cpp.sh 找不到
- codenameone - 没有互联网连接时,三星平板电脑上的设备未注册错误
- docker - 在 Docker 上本地测试 Acumos 模型的问题
- php - 在 laravel 5.6 中创建搜索表单
- ios - 想要在firebase身份验证完成后调用方法
- makefile - make: 依赖于第一个目标的多个目标的执行在创建第一个目标后停止
- vba - 我可以使用 VBA 或 Google 表格宏计算一个数字在列中仅出现一次的次数吗?
- jenkins - Jenkins: How do I set up the mailer plug-in to use Outlook.com account?