簡體   English   中英

如何生成<text />使用本機反應的循環組件?

[英]How to generate <Text /> component in loop using react native?

我想知道如何使用循環(或類似的東西)從存儲字符串數組的變量生成組件。 例如,我有一個數組:

const arr = ['Hello', 'Awesome', 'Stack','Over','Flow', 'Have', 'A', 'Nice', 'Day'];

我寫了這個方法:

function renderT() {
  return arr.map(obj => {
    <Text>{obj}</Text>;
  });
}

然后我在我的render()方法的return語句中調用它:

return (
  <View style={styles.row}>{renderT()}</View>
)

結果我在屏幕上沒有任何錯誤或文本。 我嘗試使用不同類型的循環forforEachmap並且它沒有用。 您能否指出我或建議我如何實施它的正確方法?

你應該更換

function renderT() {
  return arr.map(obj => {
    <Text>{obj}</Text>;
  });
}

這樣:

function renderT(arr) {
  return arr.map(obj => {
    return <Text>{obj}</Text>;
  });
}

和這個:

return (
  <View style={styles.row}>{renderT()}</View>
)

這樣:

return (
  <View style={styles.row}>{renderT(arr)}</View>
)

這兩個錯誤是 function renderT 中缺少返回和缺少參數。 然后你必須用正確的參數(你的數組)調用你的 function 。

arr上的map function沒有返回任何東西,這就是你沒有看到任何文本的原因。

嘗試將您的 function renderT()替換為:

function renderT() {
  return arr.map(obj => (<Text>{obj}</Text>));
}

(只需將您的<Text />值周圍的{}替換為()

有一些微妙之處需要注意,如果錯過,將導致錯誤和/或意外行為。 考慮對您的代碼進行以下調整,以解決運行時錯誤:

function renderT() {

  // Ensure arr is defined in scope of, or is "visible" to, renderT()
  const arr = ['Hello', 'Awesome', 'Stack','Over','Flow', 'Have', 'A', 'Nice', 'Day'];

  return arr.map((obj, index) => {
    // Compose a unique key for the text element. A unique key is need when 
    // rendering lists of components
    const key = index;

    // Add return to ensure the text element is returned from map callback
    return <Text key={key}>{obj}</Text>;
  });
}

需要注意的是key prop - 這應該為在列表中呈現的組件提供(即, <Text>在您的情況下)。

此處詳細說明了需要key道具的原因。 呈現的每個項目的每個key都必須是唯一的 - 通常您應該避免使用映射回調的index ,但是不能保證arr中值的唯一性,這是必要的。

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM