通过currying简化onPress?

时间:2018-01-24 22:20:30

标签: javascript react-native refactoring currying

我正在测试如何将两个非常相似的功能组合成一个以减少我的代码库,并且想知道是否可以通过currying来完成。这对我来说是一个新概念,所以我失败了,现在正在寻求帮助。



const yesNoEnum = {
  none: null,
  no: 0,
  yes: 1,
};  

  noButtonOnPress = () => {
    const isSelected = this.state.selected === yesNoEnum.no;

    if (isSelected) {
      this.setState({
        selected: yesNoEnum.none,
      });
      return;
    }

    this.setState({
      selected: yesNoEnum.no,
    });
  }

  yesButtonOnPress = () => {
    const isSelected = this.state.selected === yesNoEnum.yes;

    if (isSelected) {
      this.setState({
        selected: yesNoEnum.none,
      });
      return;
    }

    this.setState({
      selected: yesNoEnum.yes,
    });
  }
  
    isSelected = () => {
    const selected = {
      no: this.state.selected === yesNoEnum.no,
      yes: this.state.selected === yesNoEnum.yes,
    };




我想知道是否可以合并noButton和yesButton点击。这是我之前尝试过的:



  handleButtonPress = (shouldCheckYes) = () => {
    const isSelected = this.state.selected === shouldCheckYes ? yesNoEnum.yes : yesNoEnum.no;

    if (isSelected) {
      this.setState({
        selected: yesNoEnum.none,
      });
      return;
    }

    this.setState({
      selected: shouldCheckYes ? yesNoEnum.yes : yesNoEnum.no,
    });
  }




0 个答案:

没有答案