简体   繁体   English

React Native:功能组件中的getter函数?

[英]React Native: getter function in functional component?

I am new to React/React Native and having problems returning the value of a function into my template.我是 React/React Native 的新手,在将函数的值返回到我的模板时遇到了问题。 My Component, which is a functional component, receives a prop called item .我的组件是一个功能组件,它接收一个名为item的道具。 I retrieve a value from that item after a simple calculation, but I'm getting different errors for each way I try to return the value in the template.经过简单计算后,我从该项目中检索了一个值,但是对于我尝试返回模板中的值的每种方式,我都遇到了不同的错误。

Last I tried is:我最后尝试的是:

getMaxPercent() 
{
  let max = _.maxBy(props.item.discounts, function(discount) {
    return discount.sale;
  });
  return max;
}

In template like this:在这样的模板中:

<Text style={{ fontSize:17, color:'white', fontWeight:'bold' }}>
  { getMaxPercent() }% Off
</Text>

I also tried:我也试过:

const getMaxPercent = () => {}

Coming from a vue background react just seems so... verbose.来自 vue 背景的 react 看起来如此......冗长。 Is there a react equivalent to computed properties?是否有与计算属性等效的反应?

Try this,尝试这个,

function getMaxPercent() 
    {
        let max = _.maxBy(props.item.discounts, function(discount) {
            return discount.sale;
        });
        return max.sale;
    }

reference - https://www.geeksforgeeks.org/lodash-_-maxby-method/参考 - https://www.geeksforgeeks.org/lodash-_-maxby-method/

Is there a react equivalent to computed properties?是否有与计算属性等效的反应?

The React equivalent to computed properties is just standard variables, declared in the body of the component function. React 等价于计算属性只是标准变量,在组件函数的主体中声明。 The function runs every time props are changed, so these will be re-calculated then.每次更改 props 时该函数都会运行,因此这些将重新计算。

You don't need the additional function at all — you can just directly assign max to a variable.你根本不需要额外的函数——你可以直接将max分配给一个变量。

const Component = (props) => {
  const max = _.maxBy(props.item.discounts, function(discount) {
    return discount.sale;
  });

  return (
    <Text style={{ fontSize:17, color:'white', fontWeight:'bold' }}>
      { max }% Off
    </Text>
  );
};

If you don't want the dependency on lodash you can roll your own simple max finder to return the maximum sale property.如果您不想依赖 lodash,您可以使用自己的简单 max finder 来返回最大sale属性。

const getMaxPercent = (discounts) =>
  Math.max(...discounts.map(({ sale }) => sale));

 const getMaxPercent = (discounts) => Math.max(...discounts.map(({ sale }) => sale)); const discounts = [ { id: 0, sale: 3.5 }, { id: 1, sale: 13.5 }, { id: 2, sale: 13 }, { id: 3, sale: 10 }, { id: 4, sale: 7.8 } ]; console.log(getMaxPercent(discounts));

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

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