reactjs - React Hook List 大小 - React Native
问题描述
我目前正在研究钩子,我正在尝试在单击按钮时创建一个句子,并验证它们是否正确。但是,要做到这一点,我的列表最多只能有 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
解决方案
我假设您正在处理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} />
推荐阅读
- amazon-web-services - 我可以通过 Spring Boot 应用程序从 Redis 或某些 aws 服务读取外部配置吗
- java - 我怎样才能找到从一个瓷砖到另一个瓷砖必须传递的所有瓷砖
- php - 用长或复杂的形式在 PHP 中执行 POST 查询的最佳方法?
- python - 绘制很多点让我的电脑死机
- python - 如何在 python 电子邮件模块发送的表格中添加垂直滚动条?
- python - 改变神经网络中 Sigmoid 激活的阈值
- c++ - 成员不可访问 C++
- laravel - 我需要在 laravel teelscope 之后迁移
- java - 如何通过将所有路径作为参数传递来获取 JSON 字段
- ios - 集合视图显示 cellForItemAt 中的单元格数量较少