React Native "this.setState不是一个函数

React Native "this.setState is not a function"

本文关键字:函数 一个 Native quot setState this React      更新时间:2023-09-26

我从react native开始,并试图将一些动作绑定到类方法,但我得到一些关于未找到方法的错误。

I tried binding:

class AccountsScreen extends Component {
  constructor (props) {
    super(props)
    this.userChange = this.userChange.bind(this)
    this.state = {
      user: '',
      password: ''
    }
  }
  render () {
    return (
      <View>
      <Text>Pass</Text>
      <TextInput
          onChange={this.userChange}
      />
      </View>
    )
  }
  userChange (user) {
    this.setState({user: user})
  }
}

和箭头函数

class AccountsScreen extends Component {
  constructor (props) {
    super(props)
    this.state = {
      user: '',
      password: ''
    }
  }
  render () {
    return (
      <View>
      <Text>Pass</Text>
      <TextInput
          onChange={(user) => this.userChange(user)}
      />
      </View>
    )
  }
  userChange (user) {
    this.setState({user: user})
  }
}

但是我一直得到相同的错误:

"。setState不是一个函数"

完全卡住了。什么好主意吗?

实际上不需要创建一个函数来设置你的状态,你可以这样做

<TextInput onChangeText={(user) => this.setState({user: user})} />

其实这是个愚蠢的错误。我使用onChange而不是onChangeText方法....