How to use components' this.state and functions while customising the Navigation Bar?
I successfully customized my navigation bar of a tab containing a search area. I expect to tap the search icon to refresh the list based on user entry. This should use my component's state and some functions.
When I enter some search criteria or when I trigger the search function, I get a this.state is undefined. Any idea?
// Add `search`to your component's state
constructor(props) {
super(props);
this.state = {
search: 'test',
// ... Your other component's state
};
}
// Customize your component navigation bar
static renderNavigationBar(props) {
console.log('renderNavigationBar', props);
console.log('this.state', this.state.search); // this.state is undefined
console.log('this.state', props.component().state.search); // never trigger this line and never render the view if I keep this line. No error occurred
return (
<View style={{height: 60}}>
<Text style={props.navigationState.titleStyle}>
{props.title}
</Text>
<TextInput ref="search"
style={{ width: 250, height: 30, backgroundColor: 'red' }}
value='this.state.search' // if I keep this.state the view is never render, no error occurred
onChangeText={ (text) => this.setState({ search: text }) } // This makes a this.setState undefined
/>
<TouchableOpacity style={props.navigationState.rightButton} onPress={this.processSearch}>
<Icon name="ios-search" size={25} color="white" />
</TouchableOpacity>
</View>
);
}
// The function to process the search operations and refresh the data
processSearch() {
console.log('You are searching for:', this.state.search);
}
this.setState or this.stateis undefined.Any idea?
Thanks a lot
Please study about Javascript more - this cannot be used within static functions...
I know this is a pure Javascript way of programming.
However, I was wondering how to achieve creating a statefull "link" between the custom navigation bar and its component?
@KBLNY I know this is old, but you can define the button/navbar via a function within a component. You call Actions.refresh to add props such as title or renderRightButton, etc.
For example within componentWillMount:
Actions.refresh({
renderRightButton: () =>
NavigationEditRightButton(propsToPass)
});
@sheparddw thank you so much. I can't believe I didn't think about it but I didn't, thanks again. It really helped.
Most helpful comment
@KBLNY I know this is old, but you can define the button/navbar via a function within a component. You call Actions.refresh to add props such as title or renderRightButton, etc.
For example within componentWillMount:
Actions.refresh({ renderRightButton: () => NavigationEditRightButton(propsToPass) });