反应原生中使用函数的差异 [英] Difference in using functions in react-native

查看:51
本文介绍了反应原生中使用函数的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些组件我传递了一个函数。

Lets say I have some component wo which I pass a function.

export default class SomeComp extends Component {
    constructor(props) {
        super(props);
    }

    _someFunc = () => {
        return ...
    }

    render() {
        return (
            <View
                onLayout={this._someFunc()}
            />

OR

            <View
                onLayout={() => {this._someFunc()}}
            />

        )
    }
}

<$ c $之间的区别在哪里c> onLayout = {this._someFunc()} 和 onLayout = {()=> {this._someFunc()}}

推荐答案

差异实际上取决于如何以及何时<$触发c $ c> onLayout 。

The difference depends really how and when onLayout is triggered.


  • onLayout = {this ._someFunc()}

每次渲染组件时, onLayout prop将从 this._someFunc()函数中获取返回值。换句话说,该函数将在每个渲染上运行。

Each time your component is rendered the onLayout prop will get the return value from the this._someFunc() function. In other words, the function will run on every render.

onLayout = {()=> {return this._someFunc()}} onLayout = {()=> this._someFunc()}

每次渲染组件时, onLayout prop将引用绑定到一个匿名函数,该函数包含对 _someFunc()函数的调用。除非以某种方式触发 onLayout ,否则后一个函数不会执行。

Each time your component is rendered the onLayout prop will bind the reference to an anonymous function which contains the call to the _someFunc() function. The latter function doesn't get executed unless onLayout is somehow triggered.

例如,假设以下组件:

class MyApp extends React.Component {

  _someFunc = () => {
    return "bar";
  }

  render() {
    return(
      <div>
        <A foo={this._someFunc()} />
        <B foo={() => {return this._someFunc()}} />
      </div>
    );
  }
}

const A = ({foo}) => {
  console.log(foo);  //prints "bar"
  return <div>A</div>;
}

const B = ({foo}) => {
  console.log(foo);  //prints the reference to _someFunc()
  console.log(foo());  //prints "bar"
  return <div>B</div>;
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

在组件 A 中, foo prop将获得<$ c $的值c>bar。

In component A the foo prop will get the value of "bar".

在组件 B foo prop将是对稍后可以调用的函数的引用。该函数将依次调用 _someFunc ,它将返回bar。因此,如果在组件 B 中想要获取该值,则需要使用 this.props.foo()。

In component B the foo prop will be a reference to a function that you can later call. That function will in turn call _someFunc which will return "bar". So if in component B you want to get the value, you need to call it with this.props.foo().

这篇关于反应原生中使用函数的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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