【问题标题】:Failed prop type: The prop `onPress` is marked as required in `Button`, but its value is `undefined`失败的道具类型:道具`onPress`在`Button`中标记为必填,但其值为`undefined`
【发布时间】:2018-11-28 08:09:57
【问题描述】:

作为反应原生的新手,我真的不知道这个错误是什么以及如何解决这个错误。这是我正在处理的代码。

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

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

【问题讨论】:

  • 在构造器上使用this.submithandler()this.submithandler = this.submithandler.bind(this)

标签: javascript react-native


【解决方案1】:

React 移除了 ES6 组件类中的“自动绑定”。

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

解决方案:在render()中绑定

    onPress={this.submithandler.bind( this )} 

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

        onPress={() => this.submithandler()} 

【讨论】:

    【解决方案2】:

    onPress={() =&gt; this.submithandler()}

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 2022-01-05
      • 2019-05-21
      • 2020-01-14
      • 2019-07-15
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多