我试图在 header 中调用参数化函数,但无法找到传递参数的方法。
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
在 navigationOptions
函数的 static
上下文中没有任何意义,所以你不能在那里使用它来调用搜索函数
。
有一种方法可以将参数添加到 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 />);
}
}
关于android - 如何从 React Navigation Header Ba 中调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346613/