【问题标题】:Call a function expression with args within render() - react native在 render() 中调用带有 args 的函数表达式 - 反应原生
【发布时间】:2018-08-24 10:06:45
【问题描述】:

所以我阅读了 this article Atinder Singh 关于如何加快反应原生应用程序的 6 种方法。

TLDR; “尽早绑定,不要在渲染中创建函数。 这样做:

constructor(props) {
    super(props);
    this.doWork = this.doWork.bind(this);
  }
doWork() {
    // doing some work here.
    // this.props.dispatch....
  }

  render() {
    return <Text onPress={this.doWork}>Do Some Work</Text>
  }

}

不是

<Text onPress={ () => this.doWork() }>Do Some Work</Text>

<Text onPress={ this.doWork.bind(this) }>Do Some Work</Text>

因为 render 被非常频繁地调用,并且每次您执行上述任何两件事时,都会创建一个新函数。" - Oct/13/2017

在我的环境中,每次渲染都会调用函数this.doWork。所以我把它改成了const doWork = () =&gt; {...} 工作正常。但是我如何用参数调用 fct 呢?当我执行this.doWork(x, y) 时,每次渲染都会再次调用 fct。

有没有一种有效的方法来调用这个 fct 而无需在技术上为每次渲染创建一个新的? 非常感谢您的帮助!

【问题讨论】:

  • 创建新函数是什么意思?
  • 你真的有性能问题吗?

标签: reactjs function react-native expression render


【解决方案1】:

1.有没有一种有效的方法来调用这个 fct 而无需在技术上为每次渲染创建一个新的?

2。但是如何使用参数调用 fct?、

您可以使用function currying

doWork = (param) =>(e)=>{

    console.log('Event', param);
};

内部渲染:

 render(){
         return <Text onPress={this.doWork('someHardValOrProp')}>Do Some Work</Text>
    }

工作React#codesandbox示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 2020-04-15
    • 1970-01-01
    • 2014-10-22
    • 2019-01-05
    • 1970-01-01
    • 2021-01-30
    • 2020-04-13
    相关资源
    最近更新 更多