【问题标题】:React native, "this" keyword is undefiedReact Native,“this”关键字未定义
【发布时间】:2020-05-04 21:10:29
【问题描述】:

所以我想使用this.props.navigation.navigate(),但我收到一条错误消息说未定义。 在 stockOverflow 中阅读后,我看到我需要声明一个这样的构造函数

constructor(props) {
    super(props);
    }

但是这一直给我一个错误说“;”无论我做什么都是意料之中的,这是我的代码的简化版本

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>
 )

}

【问题讨论】:

  • 您忘记以&gt; 结束&lt;TextInput 开始标签。 TouchableHighlight 也一样
  • 函数组件中没有有效的this。只需使用您收到的props 作为参数即可。
  • Emile Bergeron 你能解释一下吗
  • 这意味着——没有“这个”,你也不需要一个。 “props”是一个参数,而不是实例属性。
  • 只需删除this.并保留以下props.navigation.navigate("WalkThru")即可。

标签: javascript reactjs react-native jsx


【解决方案1】:

正如 Emile Bergeron 所建议的,您应该使用 props,因为 this 关键字仅适用于基于类的组件。

基于类的组件如下所示。

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>
    )
  }
}

此外,我建议您研究一下 React / React-Native 中无状态功能组件和类组件之间的区别。

【讨论】:

  • 我一定会调查的,但这实际上不起作用export default (props) =&gt; { 是有效的,因为在那之后我还有其他一些使用道具的值
猜你喜欢
  • 2018-05-07
  • 2020-11-06
  • 2020-03-31
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
相关资源
最近更新 更多