代码之家  ›  专栏  ›  技术社区  ›  Vadym Harkusha

呈现具有不同onPress React Native的多个按钮

  •  0
  • Vadym Harkusha  · 技术社区  · 6 年前

    stackoverflow 但对我没用。

    class App extends React.Component {
      state = {
        loading: false,
        isModalVisible: false
      };
    
      toggleModal = () => {
        this.setState({ isModalVisible: !this.state.isModalVisible });
      };
    
      testfunc = () => {
        console.log("this f***ng WORKS");
      };
    
      renderButtons = () => {
        const buttons = [
          {
            title: "I have no clear direction",
            action: () => console.log("this WORKS")
          },
          { title: "I have some idea of what i want", action: () => this.testfunc },
          { title: "I know exactly what i want", action: this.toggleModal }
        ];
    
        buttons[0].action();
        buttons[1].action;
        buttons[2].action;
    
        return buttons.map((i, index) => {
          return (
            <View style={{ marginTop: 20, width: "100%" }} key={index}>
              <OnboardingButton
                title={i.title}
                loading={this.state.loading}
                onPress={() => i.action}
              />
            </View>
          );
        });
      };
    }
    

    当这个屏幕被渲染时,我得到如下结果:

    this WORKS
    

    当我点击任何一个按钮时,什么都不会发生。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Tholle    6 年前

    通过写作 onPress={() => i.action} 您正在创建一个新的内联函数,该函数返回 action 那个按钮的功能。这个 对于第二个按钮,它还创建了一个新函数,返回 this.testfunc 功能。

    只要给函数一个引用,它就会按预期工作。

    class App extends React.Component {
      state = {
        loading: false,
        isModalVisible: false
      };
    
      toggleModal = () => {
        this.setState({ isModalVisible: !this.state.isModalVisible });
      };
    
      testfunc = () => {
        console.log("this f***ng WORKS");
      };
    
      renderButtons = () => {
        const buttons = [
          {
            title: "I have no clear direction",
            action: () => console.log("this WORKS")
          },
          { title: "I have some idea of what i want", action: this.testfunc },
          { title: "I know exactly what i want", action: this.toggleModal }
        ];
    
        return buttons.map((i, index) => {
          return (
            <View style={{ marginTop: 20, width: "100%" }} key={index}>
              <OnboardingButton
                title={i.title}
                loading={this.state.loading}
                onPress={i.action}
              />
            </View>
          );
        });
      };
    
      render() {
        // ...
      }
    }