【问题标题】:React Hook List size - React NativeReact Hook List 大小 - React Native
【发布时间】:2020-02-06 07:29:22
【问题描述】:

我目前正在研究钩子,我正在尝试在单击按钮时创建一个句子,并验证它们是否正确。但是,要做到这一点,我的列表最多只能包含 5 个单词,但我在这样做时遇到了麻烦。

这个想法是,当列表达到 5 个值时,它具有最大大小。当添加另一个值时,它会弹出第一个值(索引 0)并添加最后一个值。

这是我的代码:

  const [sentence, setSentence] = useState([]);

  if(sentence==='HelloYouAreMyFriend'){
    console.log('sentence')
  }

        </View>
  <View> 
  {selectedWord.word.map(word => (
    <TouchableOpacity key={word}
onPress={() => setCount(sentence + word )}

  }>

Example 
        // 1 button click: Hello
        // 2 button click: HelloYou
        // 3 button click: HelloYouAre
        // 4 button click: HelloYourAreMy
        // 5 button click: HelloYourAreMyFriend
        // 6 button click: YourAreMyFriendJosh 
        Need SIZE max ==> 5 words in the list

【问题讨论】:

  • count 变量的用途是什么?
  • count 是一个逐个添加单词的列表
  • 提示:始终为变量和函数使用有意义的名称。谢谢

标签: reactjs react-native react-hooks


【解决方案1】:

我假设您正在处理 handlePlaySound 函数中的所有内容。

const[sentence, setSentence] = useState([]);

const handlePlaySound = (event) => {
const word = event.target.key
const localSentence = [...sentence]; //because you never mutate the state
  if (localSentence.length < 5) {
    setSentence([...localSentence], word)
  } else { 
    localSentence.splice(0,1);
    setSentence([...localSentence], word);
  }
}

从组件中你应该在事件中传递单词

<TouchableOpacity key={word} onPress={handlePlaySound} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多