如何在地图循环中调用函数(反应本机)?

时间:2020-06-02 00:12:32

标签: react-native

这是我的代码。我不确定存在什么错误。

当我单击图像按钮时,它将完全调用适当的功能。 如果单击第一个按钮,它将正确调用toggleBooks()函数。 然后在该函数中,我想使用vidMute状态值。

所以我尝试了console.log('Video toggle', this.state.vidMute);,但它给了我如下图所示的错误。

但是,如果我打印console.log('Video toggle'),则效果很好。 如何在该函数中使用状态值?

enter image description here

export default class Video extends Component {
    constructor(props) {
        super(props)
        this.state = {
            vidMute: false,
            audioShow: false,
            callShow: false,
            btn: [
                { func: this.toggleAudio, url: magic, de_url: de_magic },
                { func: this.endCall, url: endcall, de_url: de_endcall },
                { func: this.toggleBooks, url: camerarotate, de_url: de_camerarotate },
            ],
        };
    this.toggleAudio = this.toggleAudio.bind(this)
    this.endCall = this.endCall.bind(this)
    this.toggleBooks = this.toggleBooks.bind(this)
    }

    toggleBooks() {
        console.log('Video toggle', this.state.vidMute);
    }
    endCall() {
        console.log('Call toggle', this.state.audioShow);
    }
    toggleAudio() {
        console.log('Audio toggle', this.state.callShow);
    }

    render() {
        return (
            <View>
                {
                    this.state.btn.map((item, index) => (
                        <TouchableOpacity key={index} style={styles.iconStyle} activeOpacity={0.4} onPress={item.func}>
                            <Image source={this.state.lockState ? item.de_url : item.url} style={{ width: 70, height: 70 }} />
                        </TouchableOpacity>
                    ))
                }
            </View>
        )
    }

}

1 个答案:

答案 0 :(得分:1)

this是指函数的上下文,而不是组件的上下文。您可以尝试像这样绑定您的方法:

this.myMethod = this.myMethod.bind(this);

在您的构造函数中。

或者使用粗箭头模式(强烈建议),该模式会自动包括对组件上下文的绑定。

这里是a binding example on stackblitz

这是代码:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      items:[
        {name:"item 1", func: () => this.test()},
        {name:"item 2", func: () => this.test2()}
      ]
    };

    this.test = this.test.bind(this);
  }

  test() {
    console.log('Hi', this.state.name);
  }

  test2() {
    console.log('Hello', this.state.name); // Note this is not binded
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p onClick={this.test}>
          Start editing to see some magic happen :)
        </p>

        <div>
        {
          this.state.items.map(item => <div onClick={() => item.func()}>{item.name}</div>)
        }
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
相关问题