簡體   English   中英

React Native:功能組件中的getter函數?

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

我是 React/React Native 的新手,在將函數的值返回到我的模板時遇到了問題。 我的組件是一個功能組件,它接收一個名為item的道具。 經過簡單計算后,我從該項目中檢索了一個值,但是對於我嘗試返回模板中的值的每種方式,我都遇到了不同的錯誤。

我最后嘗試的是:

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

在這樣的模板中:

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

我也試過:

const getMaxPercent = () => {}

來自 vue 背景的 react 看起來如此......冗長。 是否有與計算屬性等效的反應?

嘗試這個,

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

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

是否有與計算屬性等效的反應?

React 等價於計算屬性只是標准變量,在組件函數的主體中聲明。 每次更改 props 時該函數都會運行,因此這些將重新計算。

你根本不需要額外的函數——你可以直接將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>
  );
};

如果您不想依賴 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