简体   繁体   中英

React native, "this" keyword is undefied

so I wanted to use this.props.navigation.navigate() and I got an error message saying undefined. after reading here in stockOverflow I saw that I needed declare a constructor like this

constructor(props) {
    super(props);
    }

however this keeps giving me an error saying ";" is was expected regardless of what I do, here is a simplified version of my code

const activityStyles = ActivitiesStyles.createStyles()
export default (props) => {
    const {item: event, sensorID, homeInfo} = props

  return (
<View style={activityStyles.linkContent} underlayColor={Colors.navigationBkgdActive}>
    <View style={{flex: 0.60, flexDirection: 'row'}}>
        <TouchableHighlight onPress={(event)=>{this.props.navigation.navigate("WalkThru")}}>
            <SensorIcon style={iconStyle} size={Typography.bodyLineHeight} type={event.type} />
        </TouchableHighlight>
        <TextInput
            placeholder={event.type}
            autoCapitalize={true}
            style={activityStyles.text}>
        </TextInput>
    </View>
</View>
 )

}

As Emile Bergeron suggested, you should go with props since this keyword is available only for Class-Based components.

A class based component would be as follows.

export default class componentName extends Component {
  constructor(props) {
    super(props)

    this.state = {

    }
  }

  render() {
    return (
        <TouchableHighlight
          <View style={activityStyles.linkContent} underlayColor={Colors.navigationBkgdActive}>
            <TouchableHighlight onPress={(event)=>{this.props.navigation.navigate("WalkThru")}}>
              <SensorIcon style={iconStyle} size={Typography.bodyLineHeight} type={event.type} />
            </TouchableHighlight>
              <TextInput
                placeholder={event.type}
              </TextInput>
          </View>
        </TouchableHighlight>
    )
  }
}

Furthermore, I can propose you look into differences between Stateless Functional Components and Class Components in React / React-Native.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM