0

Im new to react and are experimenting a bit with react-native-video. Im trying to change a prop in the react-native-video library by clicking on a touchable element. But Im getting the errormessage:

undefined is not an object (evaluating 'this.state.setState')

Im sure this is an easy problem. I basically just want to find out how to initiate, call and change the state of the props when I am touching the defined Touchable area. In this example I want to change the rate from 0.1 to 1.

Here is my code:

type Props = {};
export default class App extends Component<Props> {
  state = {
    rate: 0.1,
  };

  _onPressButton() {
    Alert.alert('You tapped the button!')
    this.state.setState({ rate: 1 });
  }

  render() {

    return (
      <View style={styles.container}>

        <Video
          source={require('./assets/grid.mp4')}
          ref={(ref) => {
            this.player = ref
          }}                                      
          onBuffer={this.onBuffer}                
          onError={this.videoError}               
          style={styles.backgroundVideo}
          rate={this.state.rate}
        />

        <TouchableWithoutFeedback onPress={this._onPressButton}>
          <View style={styles.square1}>
            <Text style={styles.welcome}>My text</Text>
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  }
}
4

3 回答 3

1

您的onPressButton方法不受上下文约束,正如上面提到的答案,您需要使用this.setState({ rate: 1 });.

您可以添加一个构造函数并使用.bind(this)如下:

constructor(props) {
    super(props);

    this. _onPressButton = this. _onPressButton.bind(this)
  }

或者您可以使用如下自动绑定箭头功能:

_onPressButton = () => {
    Alert.alert('You tapped the button!')
    this.setState({ rate: 1 });
  }
于 2019-06-17T13:10:11.490 回答
1

正如错误所述:

undefined 不是对象(评估“this.state.setState”)

this.state 没有名为 setState 的对象

改变:

_onPressButton() {
    Alert.alert('You tapped the button!')
    this.state.setState({ rate: 1 });
  }

至:

_onPressButton() {
    Alert.alert('You tapped the button!')
    this.setState({ rate: 1 });
  }

此外,您需要更改:

<TouchableWithoutFeedback onPress={this._onPressButton}>

<TouchableWithoutFeedback onPress={() => this._onPressButton()}>
于 2019-06-17T13:00:58.360 回答
1

您没有绑定您的功能。

_onPressButton() {
    Alert.alert('You tapped the button!')
    this.state.setState({ rate: 1 });
  }

应该是这样的箭头函数

_onPressButton = () => {
    Alert.alert('You tapped the button!')
    this.state.setState({ rate: 1 });
  }

或者您需要创建一个构造函数并this._onPressButton.bind(this)在其中写入。

于 2019-06-17T13:07:44.120 回答