我正在使用React Navigationv5的setOptions应用程序接口来定制我的标题按钮,并访问功能组件中的函数:
import React, { useState, useLayoutEffect } from 'react';
import { View, TouchableOpacity, TextInput } from 'react-native';
export default ({ navigation }) => {
const [text, setText] = useState('initialValue');
console.log('render - text is now: ' + text);
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity onPress={handleSubmit}>
<View style={{marginRight: 18, borderWidth: 2, borderColor: 'white', borderRadius: 17.5, width: 35, height: 35}}>
{/* FontAwesome icon omitted for brevity */}
</View>
</TouchableOpacity>
)
});
}, [navigation]);
const handleSubmit = () => {
console.log('submit - text is now: ' + text);
};
return (
<View style={{flex: 1, padding: 20}}>
<TextInput
style={{width: '100%'}}
multiline
autoGrow
value={text}
onChangeText={text => setText(text)}
/>
</View>
);
};当我使用这个组件并更改文本时,我可以看到正确的"render - text is now:...“控制台上的输出。
但是,当我单击header按钮并调用提交方法时,我看到"submit - text is now: initialValue",而不管我所做的更改。
我看不出我可能做错了什么,请给我建议。
版本:* react: 16.11.0 * react-native: 0.62.2 * @react-navigation/native: 5.5.1
发布于 2020-06-14 02:00:50
您必须将文本作为依赖项传递,useLayoutEffect才能正常工作
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity onPress={handleSubmit}>
<View style={{marginRight: 18, borderWidth: 2, borderColor: 'white', borderRadius: 17.5, width: 35, height: 35}}>
{/* FontAwesome icon omitted for brevity */}
</View>
</TouchableOpacity>
)
});
}, [navigation,text]);https://stackoverflow.com/questions/62363624
复制相似问题