调用函数onPress React Native

Som*_*ame 3 javascript reactjs react-native

我只是想知道如何调用函数onPress.我设置了这样的代码:

export default class Tab3 extends Component {
    constructor(props) {
        super(props);
        this.state = {myColor: "green"};
    }

    handleClick = () => {
        if (this.state.color === 'green'){
           this.setState({myColor: 'blue'});
        } else {
           this.setState({myColor: 'green'});
        }
    }

    render() {
     return(
      <View>
           <Icon
            name='heart'
            color={this.state.myColor}
            size= {45}
            style={{marginLeft:40}}
            onPress={() => handleClick(this)}                                 
            />
      </View>
      )};
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这个时,我会收到错误 can't find variable handleClick

请帮忙.我只想知道如何将函数绑定到click事件.

小智 11

聚会有点晚了,但如果有人需要,只想把它留在这里

export default class mainScreen extends Component {

handleClick = () => {
 //some code
}

render() {
 return(
  <View>
       <Button
        name='someButton'
        onPress={() => {
            this.handleClick(); //usual call like vanilla javascript, but uses this operator
         }}                                 
        />
  </View>
  )};
Run Code Online (Sandbox Code Playgroud)


eva*_*nal 6

在你渲染中你正在设置错误的处理程序,试一试;

 <View>
       <Icon
        name='heart'
        color={this.state.myColor}
        size= {45}
        style={{marginLeft:40}}
        onPress={this.handleClick}                                 
        />
  </View>
Run Code Online (Sandbox Code Playgroud)

您正在使用的语法对于声明内联或其他内容的匿名函数是有意义的,但由于您的处理程序是在类上定义的,因此您只需this.functionName在props中引用它(而不是调用它).