使用不同的onPress React Native渲染多个按钮

时间:2018-11-16 22:03:57

标签: reactjs react-native

我试图用不同的文本和动作onPress()渲染3个按钮。 我在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>
      );
    });
  };
}

我仅使用console.log()进行测试。 作为渲染此屏幕时的输出,我得到了:

this WORKS

当我单击任何按钮时,什么也没有发生。

1 个答案:

答案 0 :(得分:0)

通过编写onPress={() => i.action},您将创建一个新的内联函数,该函数将返回该按钮的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() {
    // ...
  }
}