简体   繁体   English

将函数传递给React中的组件

[英]Passing functions to components in React

Say I have a class component called 'Parent' which renders a component called 'Child': 假设我有一个名为“Parent”的类组件,它呈现一个名为“Child”的组件:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            someProperty = 'some value',
        };
}

setProperty: newValue => {
    this.setState({someProperty: newValue});
}

render() {
    return < Child setProperty: {this.setProperty} />
}

and the Child component: 和子组件:

const Child = props => {
    return <button onClick={props.setProperty('new value')} />
}

So this works, and it makes sense to me: We're passing a reference to setProperty, which is then whenever a child component is clicked. 所以这是有效的,这对我来说很有意义:我们传递对setProperty的引用,然后只要点击子组件就可以了。

In many tutorials, I see the following code (in Parent): 在许多教程中,我看到以下代码(在Parent中):

render() {
    return < Child setProperty: {newValue => this.setProperty(newValue) />
}

Is there a benefit to doing this when passing a function along? 传递函数时,这样做有什么好处?

Is there a benefit to doing this when passing a function along? 传递函数时,这样做有什么好处?

It depends on how this.setProperty is defined. 这取决于如何定义this.setProperty It is either unnecessary to do it that way or necessary ** because it wouldn't work otherwise. 没有必要这样做或必要**因为它不会起作用。

It all comes down to how this works: 这一切都归结为this是如何工作的:

In "normal" functions, the value of this depends on how the function is called . 在“正常”的功能,价值this取决于函数是如何被调用 So if this.setProperty is such a normal function, then passing it to the child with setProperty={this.setProperty} makes it impossible for the child to call the function so that this refers to the parent component, which means calling this.setState inside the function will fail. 因此,如果this.setProperty是这样的正常功能,然后将它传递给与儿童setProperty={this.setProperty}使得不可能为孩子调用功能,使得this指的是父组件,这意味着主叫this.setState函数内部将失败。

 function callMe(callback) { callback(); } const obj = { foo: 42, normalFunction() { console.log(this.foo); }, }; callMe(obj.normalFunction); // not 42 :( callMe(() => obj.normalFunction()); // 42 :) 

But if the function is an arrow function (like in your first example) or a bound function then the value of this is already predetermined and it doesn't matter how the function is called. 但是,如果该函数是一个箭头的功能(如在你的第一个例子)或绑定的功能,那么价值this已经被预定并不要紧函数是如何调用。

 function callMe(callback) { callback(); } const obj = { foo: 42, normalFunction() { console.log(this.foo); }, }; obj.boundFunction = obj.normalFunction.bind(obj); callMe(obj.boundFunction); // 42 :) callMe(() => obj.boundFunction()); // 42 :) 


Related: 有关:

-- -

**: Of course it is not "necessary" to pass the function in any specific way if one can control how the function is defined. **:当然,如果可以控制函数的定义方式,以任何特定方式传递函数都不是“必要的”。 This whole answer is only looking at why someone might be doing it this way. 这整个的答案是只盯着为什么有人可能会做这种方式。 You can avoid a certain style if you change how the function is defined. 如果更改函数的定义方式,则可以避免使用某种样式。

So there's been some controversial discussions about inline functions. 所以关于内联函数的讨论一直存在争议。 Many believe inline functions are not performant and also make the child components re-render cause of different reference of functions specially in case of using PureComponent. 许多人认为内联函数不具备性能,并且还会使子组件重新呈现,导致不同的函数引用,特别是在使用PureComponent的情况下。

IMHO to me there is no difference but why not using static functions while they're available in a any case 恕我直言,没有区别,但为什么不使用静态功能,而它们在任何情况下都可用

This is just an example that demonstrates difference between using a static function and inline functions: 这只是一个示例,演示了使用静态函数和内联函数之间的区别:

class Test extends Component {
  render() {
    return(
      <button onClick={() => this.props.onUpdate(true)}>update</button>
    )
  }
}

// could be this as handleClick is the same reference in all renders
class Test2 extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.props.onUpdate(true);
  }
  render() {
    return (
      <button onClick={this.handleClick}>update</button>
    );
  }
}

Update: Used constructor to bind the static function 更新:使用构造函数绑定静态函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM