gpt4 book ai didi

reactjs - react native / react 导航 : how do I access a component's state from `static navigationOptions` ?

转载 作者:行者123 更新时间:2023-12-03 13:13:25 24 4
gpt4 key购买 nike

当您有一个表单组件,并且需要使用导航栏中的按钮提交组件的部分状态时,您如何处理这种情况?

const navBtn = (iconName, onPress) => (
<TouchableOpacity
onPress={onPress}
style={styles.iconWrapper}
>
<Icon name={iconName} size={cs.iconSize} style={styles.icon} />
</TouchableOpacity>
)

class ComponentName extends Component {

static navigationOptions = {
header: (props) => ({
tintColor: 'white',
style: {
backgroundColor: cs.primaryColor
},
left: navBtn('clear', () => props.goBack()),
right: navBtn('done', () => this.submitForm()), // error: this.submitForm is not a function
}),
title: 'Form',
}

constructor(props) {
super(props);
this.state = {
formText: ''
};
}

submitForm() {
this.props.submitFormAction(this.state.formText)
}

render() {
return (
<View>
...form goes here
</View>
);
}
}

最佳答案

简单的设计模式

作为 @val 优秀答案的后续,以下是我构建组件的方式,以便所有参数都在 componentWillMount 中设置。我发现这让它变得更简单,并且对于所有其他屏幕来说都是一个容易遵循的模式。

static navigationOptions = ({navigation, screenProps}) => {
const params = navigation.state.params || {};

return {
title: params.title,
headerLeft: params.headerLeft,
headerRight: params.headerRight,
}
}

_setNavigationParams() {
let title = 'Form';
let headerLeft = <Button onPress={this._clearForm.bind(this)} />;
let headerRight = <Button onPress={this._submitForm.bind(this)} />;

this.props.navigation.setParams({
title,
headerLeft,
headerRight,
});
}

componentWillMount() {
this._setNavigationParams();
}

_clearForm() {
// Clear form code...
}

_submitForm() {
// Submit form code...
}

关于reactjs - react native / react 导航 : how do I access a component's state from `static navigationOptions` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43400151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com