在本机0.60.5中,无法从render方法内部使用此函数调用类函数

时间:2019-11-22 06:14:19

标签: react-native

无法在render方法中使用this.func调用类函数。

type Props = {};


export default class App extends Component<Props> {

  func = () => {
    console.log('hello')
  }

  render() {
    return (
      <View style={styles.container}>
        <Button 
          title='logIn'
          onPress={() => this.func()}
        />
      </View>
    );
  }
}

如果将func放入render方法中,则onPress = {()=> func()}可以正常工作。以前,这在其他项目中也有用。

1 个答案:

答案 0 :(得分:0)

在构造函数本身中绑定func()方法

constructor(props) {
    super(props);
    this.state = {
    };
    this.func = this.func.bind(this);
}

您发挥作用

func(){
    console.log('hello')
}

您的按钮如下所示,

<Button 
   title='logIn'
   onPress={this.func}
/>
  

由于采用这种方式,您不会每次都结束创建引用   更改以及何时调用渲染。在构造器中绑定方法   本身也可以帮助您提高性能。

我希望这对您有帮助...。谢谢:)