创建可以传递参数而不需要创建新组件的函数 [英] Create function that can pass a parameter without making a new component

查看:142
本文介绍了创建可以传递参数而不需要创建新组件的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于 React 在渲染函数中用于绑定函数的问题。



以下是不好的做法:

  render(){
< div onClick = {this.callFunction.bind(此)} />
}

因为每个re render都会在页面中添加一个新的函数,最终导致浏览器耗尽内存。



解决方案是这样做的:

  constructor(){
this.callFunction = this.callFunction.bind(this);
}

render(){
< div onClick = {this.callFunction} />
}

这个问题是当我想传入一个值到函数中。

我知道我可以让div成为一个子组件,并通过callBack传递参数,但如果div只在一次使用时看起来不合情理整个应用程序。我接受我可以做这个工作,但这不是这个问题的范围。



我也知道这个解决方案:

  render(){
< div onClick = {()=> this.callFunction.call(this,param)} />
}

没有更好的了,因为它仍然在创建一个新函数。



所以我的问题是,我如何创建一个函数来传递参数,而无需创建新组件,并且不会在每个渲染上绑定一个新的函数?

解决方案

您无法避免创建第二个组件,因为您需要将函数引用作为事件处理函数传递,这将由浏览器执行当事件触发时。所以问题不是绑定,而是你需要传递一个引用,并且引用不能接收参数。

编辑

顺便说一句,如果你不喜欢绑定或匿名箭头函数的语法和噪声您可以使用currying。

如果您发现它很有趣,我会在其他问题中发布一个示例。这不会解决问题,但它是通过一个新的参考(我觉得它是最简洁的)的另一种方法


My question is to do with the issue React has for binding functions in the render function.

The following is not good practice:

render() {
   <div onClick={this.callFunction.bind(this)}/>
}

as each re render would add a new function to the page, eventually causing the browser to run out of memory.

The solution is to do this:

constructor() {
   this.callFunction = this.callFunction.bind(this);
}

render() {
   <div onClick={this.callFunction}/>
}

The problem with this is when I want to pass a value into the function.

I know I can make the div a child component, and pass the parameter in through the callBack, but this does not seem sensible if the div is only being used once in the whole application. I accept I could make this work, but this is not the scope of this question.

I also know that this solution:

render() {
   <div onClick={() => this.callFunction.call(this, param)}/>
}

Is no better, as it is still creating a new function.

So my question is, how can I create a function that I can pass a parameter into without making a new component, and without binding a new funciton on each render?

解决方案

You can't avoid creating a second component as you need to pass a function reference as an event handler, this will be executed by the browser when the event triggers.

So the problem is not the binding but the fact that you need to pass a reference, and references can't receive parameters.

EDIT
By the way, if you don't like the syntax and noise of binding or anonymous arrow functions you can use currying.
I posted an example in a different question if you find it interesting. this won't solve the problem though, it's just another approach to pass a new reference (which i find it to be the most terse)

这篇关于创建可以传递参数而不需要创建新组件的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆