React Native中stack navigator自定义headerRight按钮报错function is not a function
嘿,我来帮你搞定这个“function is not a function”的报错!你遇到的问题主要是this绑定丢失或者navigationOptions的上下文不匹配导致的,下面给你几个具体的解决方案,照着改就能正常调用sharePost啦:
方案1:用箭头函数定义sharePost(最省心)
在class组件里,箭头函数会自动绑定组件实例的this,这样就不会出现找不到函数的问题:
import React, { Component } from "react"; import Icon from "react-native-vector-icons/MaterialCommunityIcons"; class YourScreen extends Component { // 用箭头函数定义sharePost sharePost = () => { // this.props.doShare(); console.log("DONE"); }; static navigationOptions = ({ navigation }) => { return { headerRight: () => ( <Icon name="share-variant" size={24} // 通过navigation.getParam获取绑定好的函数 onPress={navigation.getParam('onShare')} style={{ marginRight: 15 }} /> ) }; }; componentDidMount() { // 将sharePost设置为navigation参数,供headerRight调用 this.props.navigation.setParams({ onShare: this.sharePost }); } render() { // 你的页面渲染内容 return <></>; } } export default YourScreen;
方案2:手动绑定this(适合坚持用普通函数的情况)
如果还是想用普通函数定义sharePost,记得在constructor里手动绑定this:
class YourScreen extends Component { constructor(props) { super(props); // 手动绑定this到sharePost this.sharePost = this.sharePost.bind(this); } sharePost() { // this.props.doShare(); console.log("DONE"); } // 后续的navigationOptions和componentDidMount配置和方案1一致 static navigationOptions = ({ navigation }) => { return { headerRight: () => ( <Icon name="share-variant" size={24} onPress={navigation.getParam('onShare')} style={{ marginRight: 15 }} /> ) }; }; componentDidMount() { this.props.navigation.setParams({ onShare: this.sharePost }); } render() { return <></>; } }
为什么会报错?
因为static navigationOptions是组件的静态属性,它的上下文并不是组件的实例,所以直接在里面写this.sharePost会找不到对应的函数。我们需要通过navigation.setParams把组件的方法传递过去,再用navigation.getParam获取调用,这样就能确保函数的this指向正确啦!
内容的提问来源于stack exchange,提问作者Shashika Virajh
相关产品推荐
相关产品推荐

