使用render()中的args调用函数表达式 - 反应native

时间:2018-03-15 14:30:02

标签: reactjs function react-native expression render

所以我阅读了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>

OR

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

因为渲染是经常调用的,每次执行上述两项操作中的任何一项时,都会创建一个新函数。“ - 2017年10月13日

在我的环境中,每次渲染都会调用函数this.doWork。所以我将其更改为const doWork = () => {...} 工作良好。但是如何用参数调用fct?当我this.doWork(x, y)时,每次渲染都会再次调用fct。

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

1 个答案:

答案 0 :(得分:0)

  

<强> 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 示例。

相关问题