Я пытаюсь вызвать параметризованную функцию в заголовке, но не могу, так как не могу найти способ передать параметр.
class MyScreen extends React.Component {
static navigationOptions = ({ navigation }) =>
{
headerLeft: (
<SearchBar
placeholder = "Search"
round
onChangeText = {text => this.searchFunction(text)}
/>
)
};
*searchFunction(text)
{
alert( text + ' searched succesfully');
}*
componentDidMount()
{
**//I would need implementation here**
}
render()
{
return (<View />);
}
}
Зарезервированное слово this ничего не значит в контексте static функции navigationOptions, поэтому вы не можете использовать его там для вызова searchFunction.
Есть способ добавить параметры к объекту navigation, чтобы вы могли получить их в статической функции navigationOptions.
Вы можете добавить searchFunction как параметр объекта navigation и передать его атрибуту onChangeText.
Реализация выглядит так:
class MyScreen extends React.Component {
// Pass the searchFunction from the navigation params to the `onChangeText` attribute.
// It should be triggered with the `text` argument.
static navigationOptions = ({ navigation }) =>
{
headerLeft: (
<SearchBar
placeholder = "Search"
round
onChangeText = {navigation.getParam('searchFunc')}
/>
)
};
// Use arrow function to bind it to the MyScreen class.
// (I'm not sure you have to do it like this, try to use it as a normal function first)
searchFunction = (text) => {
alert( text + ' searched succesfully');
}
// Add the `searchFunction` as a navigation param:
componentDidMount() {
this.props.navigation.setParams({searchFunc: this.searchFunction})
}
// Since we pass a class function as a param
// I believe it would be a good practice to remove it
// from the navigation params when the Component unmounts.
componentWillUnmount() {
this.props.navigation.setParams({searchFunc: null})
}
render() {
return (<View />);
}
}
Отлично :) Пожалуйста. Вы должны отметить этот ответ как принятый, чтобы другие люди увидели, что на этот вопрос есть принятый ответ.
Я дам ему попробовать. Спасибо за ответ.