【问题标题】:Solution to JSX props not using inline arrow functions?JSX props 不使用内联箭头函数的解决方案?
【发布时间】:2018-11-21 08:43:28
【问题描述】:

我最近发现了为什么我不应该对组件道具使用内联箭头函数的原因,但我不知道推荐的解决方案是什么。这是我使用函数的示例:

  renderSectionFooter(isSpecialFooter) {
    return (
      <SomeFooter
        onPress={
          isSpecialFooter
            ? () => this.toggleModalVisibility('specialFooterIsVisible')
            : () => this.toggleModalVisibility('boringFooterIsVisible')
        }
      />
    );
  }

这让我有一个非常简单和干净的切换器功能:

toggleModalVisibility(modalIsVisible) { this.setState({ [modalIsVisible]: !this.state[modalIsVisible] }); }

我能看到的唯一解决方法是为每个“页脚”创建一个特殊的函数,但在我看来,这违背了拥有类似函数的最佳实践。

【问题讨论】:

  • 不管truefalse 你的onPress 都会触发同样的方法toggleModalVisibility。那么为什么不将支票移到toggleModalVisibility 内呢?
  • this.toggleModalVisibility(isSpecialFooter ? 'specialFooterIsVisible' : 'boringFooterIsVisible') 使用起来会不会更有意义?
  • 无论如何,您唯一的其他选择是使用IFFE 传递isSpecialFooter 并在按下时使用它返回一个函数
  • 或者,你可以在渲染之外创建一个适当的函数来处理逻辑,我相信这是应该做的
  • 您能否将我们链接到那些不使用内联箭头函数作为道具的原因?

标签: javascript react-native ecmascript-6 jsx


【解决方案1】:

您不应使用内联箭头函数来传递所需的值。最佳实践是将所需的值与函数绑定。您还可以有条件地绑定值。这允许单个处理程序以您提到的方式处理这两种情况。考虑以下代码:

renderSectionFooter(isSpecialFooter) {
   return (
     <SomeFooter
        onPress={this.toggleModalVisibility.bind(this, isSpecialFooter ? 'specialFooterIsVisible' : 'boringFooterIsVisible')}
      />
   );
}

【讨论】:

  • 这会不会导致与内联函数相同的问题,来源:about.usps.com/postal-bulletin/2007/html/pb22218/kit1_011.html
  • 不,它不会导致与内联函数相同的问题,因为对于内联函数,每次组件呈现时都会创建新函数。在这里,我们将所需的值与声明的 toggleModalVisibility 函数处理程序本身绑定。让我知道它仍然不清楚。
【解决方案2】:

最好的方法是使用在render() 方法和类主体中定义的方法,这样可以避免内联函数的缺点,并且可以使用箭头函数而无需绑定函数。您可以使用如下函数:

_someFunc = (isSpecialFooter) = () => {
    if (isSpecialFooter) {
        this.toggleModalVisibility('specialFooterIsVisible');
    } else {
        this.toggleModalVisibility('boringFooterIsVisible')
    }
}

renderSectionFooter(isSpecialFooter) {
    return (
      <SomeFooter
        onPress={_someFunc(isSpecialFooter)}
      />
    );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 2020-11-29
    • 2019-01-10
    • 2018-10-07
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多