我已经制作了全屏TextInput
,并且希望在按下Post button
中的NavigationBar
时执行操作。但是,由于必须将Button
在onPress
中调用的方法设置为静态方法,因此我无法访问state
。
这是我当前的代码,状态在console.log
中未定义。
import React, { Component } from 'react';
import { Button, ScrollView, TextInput, View } from 'react-native';
import styles from './styles';
export default class AddComment extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: 'Add Comment',
headerRight: (
<Button
title='Post'
onPress={() => AddComment.postComment() }
/>
),
};
};
constructor(props) {
super(props);
this.state = {
post: 'Default Text',
}
}
static postComment() {
console.log('Here is the state: ', this.state);
}
render() {
return (
<View onLayout={(ev) => {
var fullHeight = ev.nativeEvent.layout.height - 80;
this.setState({ height: fullHeight, fullHeight: fullHeight });
}}>
<ScrollView keyboardDismissMode='interactive'>
<TextInput
multiline={true}
style={styles.input}
onChangeText={(text) => {
this.state.post = text;
}}
defaultValue={this.state.post}
autoFocus={true}
/>
</ScrollView>
</View>
);
}
}
有什么想法可以完成我想要的吗?
最佳答案
我看到了you've found解决方案。对于未来的读者:
Nonameolsson在Github上发布了如何实现此目的:
在componentDidMount
中,将方法设置为参数。
componentDidMount () {
this.props.navigation.setParams({ postComment: this.postComment })
}
并在您的
navigationOptions
中使用它:static navigationOptions = ({ navigation }) => {
const { params } = navigation.state
return {
title: 'Add Comment',
headerRight: (
<Button
title='Post'
onPress={() => params.postComment()}
/>
),
};
};