失败的道具类型:道具`onPress`在`Button`中标记为必需,但其值为'undefined`

sat*_*jha 2 javascript react-native

作为新的反应本机,我真的无法弄清楚这是什么错误以及如何解决此错误.这是我正在处理的代码.

import React,{Component} from 'react';
import { StyleSheet, Text, View,TextInput ,Button,ListItem} from 'react-native';

export default class App extends React.Component {
  state={
    placename:'',
    places:[]
  }
  placeholdername =val=>{
    this.setState({
      placename:val
    })
  };

   submithandler =()=>{
    console.log('Inside placesubmithandler');
    this.setState(prevState => {
      return {
        places: prevState.places.concat(prevState.placename)
      };
    });
  };

  render() {
    const placesOutput = this.state.places.map((place, i) => (
      <ListItem key={i} placename={place} />
    ));
    return (
      <View style={styles.container}>
      <View  style={styles.inputcontainer}>
      <TextInput
      style={{width:300,borderColor:1,borderColor:"black"}}
      placeholder="An awesome place"
      value={this.state.placename}
      onChangeText={this.placeholdername}
      style={styles.placeButton}
      />
      <Button
              title="Add"
              style={styles.placeButton}
              onPress={this.submithandler}
          />
      </View>
      <View>
      {placesOutput}
      </View>
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

错误只是说onpress被标记为reuired我用于按钮是未定义的.究竟是什么问题?我从代码中删除了样式部分.

Sel*_*rim 6

React删除了ES6组件类中的"自动绑定".

代码onPress = {this.submithandler}可能会失败,因为它没有绑定任何东西.

解决方案:绑定渲染()

    onPress={this.submithandler.bind( this )} 
Run Code Online (Sandbox Code Playgroud)

另一个解决方案:Fat Arrow类方法

        onPress={() => this.submithandler()} 
Run Code Online (Sandbox Code Playgroud)