我有一个 React Native 组件,它需要用一个字母一个字母一个字母地打印字符串的字母来显示一个动画。因此,从逻辑上讲,我需要在循环中更新 React 状态挂钩,以 1 秒的间隔将字符串的每个字符附加到它。到目前为止我所拥有的是:
let [placeholder, change_placeholder] = React.useState('');
const placeholder_print = () => {
let temp = "Search for anything"
console.log("Value of temp is now: " + temp)
console.log("Length of string: " + temp.length)
for (let i = 0; i < temp.length; i++) {
console.log("Selected character is: " + temp.charAt(i))
change_placeholder(placeholder.concat(temp.charAt(i)))
console.log("Placeholder is now: " + placeholder)
}
}
以及带有状态钩子的 React 组件:
<View>
<Text>{placeholder}</Text>
</View>
是的,我知道这不会动画。但是最后for
, 的值placeholder
逻辑上应该是字符串本身,对吗?如果是这样,我可能能够setTimeout()
在 for 循环内部绕过动画部分以每秒运行一次。但是,这placeholder_print()
是运行时的输出:
[Fri Jan 15 2021 16:29:30.166] LOG Value of temp is now: Search
[Fri Jan 15 2021 16:29:30.168] LOG Length of string: 6
[Fri Jan 15 2021 16:29:30.169] LOG Selected character is: S
[Fri Jan 15 2021 16:29:30.170] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.170] LOG Selected character is: e
[Fri Jan 15 2021 16:29:30.170] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.171] LOG Selected character is: a
[Fri Jan 15 2021 16:29:30.171] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.171] LOG Selected character is: r
[Fri Jan 15 2021 16:29:30.172] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.172] LOG Selected character is: c
[Fri Jan 15 2021 16:29:30.172] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.173] LOG Selected character is: h
[Fri Jan 15 2021 16:29:30.173] LOG Placeholder is now:
当在 Python 或什至没有状态挂钩的 vanilla JavaScript 中运行类似的逻辑时,这很好用。我不知道这是否需要使用<Animated>
React Native 中的组件来实现,或者它是否是 React 状态挂钩工作方式的一些根本区别。我被困在这里,伸出援手将得到支持。