好的,不回答这个问题React native - "this.setState is not a function" trying to animate background color?我只是想在React Native中循环使视图的背景色变淡。
export default props => {
let [fontsLoaded] = useFonts({
'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
});
//Set states and hooks
//To change state 'color' - setColor('#ff0000');
const colors = ["#fff", "#ff0000", "#00ff00", "#0000ff", "#0077ff"];
const [color, setColor] = useState("#fff");
const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));
const [time, setTime] = useState(0);
//const t = colors[randNum(0, colors.length)];
//random num, exclusive
function randNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
useEffect(() => {
setBackgroundColor(new Animated.Value(0));
}, []); // this will be only called on initial mounting of component,
// so you can change this as your requirement maybe move this in a function which will be called,
// you can't directly call setState/useState in render otherwise it will go in a infinite loop.
useEffect(() => {
Animated.timing(backgroundColor, {
toValue: 100,
duration: 5000
}).start();
}, [backgroundColor]);
var bgColor = this.state.color.interpolate({
inputRange: [0, 300],
outputRange: ["rgba(255, 0, 0, 1)", "rgba(0, 255, 0, 1)"]
});
useEffect(() => {
const interval = setInterval(() => {
//setTime(new Date().getMilliseconds());
setColor("#ff0000");
}, 36000);
return () => clearInterval(interval);
}, []);
有了这个,除了var bgColor = this.state.color
会产生错误
未定义不是评估..
的对象
我不明白为什么会出现这个问题,因为我将颜色设置为useState('#fff')
,我想在样式表中将color
用作backgroundColor
。
如何正确设置?
答案 0 :(得分:1)
如果您的组件是一个函数,则不应使用this.state.
,但必须直接调用状态名称。
在您的代码中:
var bgColor = color.interpolate({...})
代替:
var bgColor = this.state.color.interpolate({...})
来自反应DOCS
阅读状态
当我们想在班级中显示当前计数时,我们 阅读this.state.count:
<p>You clicked {this.state.count} times</p>
在一个函数中,我们可以 直接使用计数:
<p>You clicked {count} times</p>
答案 1 :(得分:0)
在此示例中,不为动画值创建状态,而是使用记事初始化一次并使用计时功能对其进行更新
小吃:https://snack.expo.io/GwJtJUJA0
代码:
export default function App() {
const { value } = React.useMemo(
() => ({
value: new Animated.Value(0),
}),
[]
);
React.useEffect(() => {
Animated.loop(
Animated.sequence([
Animated.timing(value, {
toValue: 1,
duration: 1000,
}),
Animated.timing(value, {
toValue: 0,
duration: 1000,
})
])
).start();
}, []);
const backgroundColor = value.interpolate({
inputRange: [0, 1],
outputRange: ['#0dff4d', '#ff390d'],
});
return (
<View style={styles.container}>
<Animated.View style={{ width: 200, height: 100, backgroundColor }} />
</View>
);
}
答案 2 :(得分:0)
在功能组件中,您不使用this.state.abc访问组件的状态属性/变量,而是直接使用状态变量的名称。因此,您应该做的是:
var bgColor = color.interpolate({
inputRange: [0, 300],
outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
});