本文介绍了React Hook 列表大小 - React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我目前正在研究钩子,我试图在单击按钮时创建一个句子,并验证它们是否正确.但是,要做到这一点,我的列表最多只能包含 5 个字,但我很难做到这一点.

i am currently working on hooks and i am trying to create a sentence when buttons are clicked, and validating them if they are correct. However, to do this, my list has to be only 5 words max, and i am having trouble to do so.

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

The idea is that, when the list arrives to 5 values it has its maximum size. And when another value is added, it pops out the first value (of index 0) and adds the last value.

这是我的代码:

  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

推荐答案

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

I am assuming you that you are handling all stuff in handlePlaySound function.

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);
  }
}

从组件中你应该在一个事件中传递信息

and from component you should pass word in an event

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

这篇关于React Hook 列表大小 - React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:46