【问题标题】:Rendering multiple buttons with different onPress React Native使用不同的 onPress React Native 渲染多个按钮
【发布时间】:2018-11-17 06:37:43
【问题描述】:

我正在尝试使用不同的文本和操作 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

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

【问题讨论】:

  • @Tholle 不,当我点击按钮时仍然没有任何反应
  • @Tholle 它确实有效,我之前尝试过。问题是onPress()&lt;OnboardingButton&gt; 中被覆盖。无论如何感谢您的回答!

标签: reactjs react-native


【解决方案1】:

通过编写onPress={() =&gt; 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() {
    // ...
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多