我正在尝试在标头中调用参数化函数,但由于无法找到传递参数的方式而无法执行。
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 />);
}
}
答案 0 :(得分:2)
保留字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 />);
}
}