yes*_*day 0 reactjs react-native
我有以下代码(完整示例):
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Button, StyleSheet, Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const App = () => {
const [blocks, setBlocks] = useState([]);
const CreateBlockHandler = () => {
let array = blocks;
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks();
};
const MoveBlockHandler = (index, event) => {
Animated.spring(blocks[index].x, { toValue: event.nativeEvent.x }).start();
Animated.spring(blocks[index].y, { toValue: event.nativeEvent.y }).start();
};
const RenderBlocks = () => {
return blocks.map((item, index) => {
return (
<PanGestureHandler key={index} onGestureEvent={event => MoveBlockHandler(index,event)}>
<Animated.View style={[styles.block, {
transform: [
{ translateX: item.x },
{ translateY: item.y }
]
}]} />
</PanGestureHandler>
)
});
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.pancontainer}>
<RenderBlocks />
</View>
<Button title="Add block" onPress={CreateBlockHandler} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
pancontainer: {
width: '95%',
height:'75%',
borderWidth: 1,
borderColor: 'black'
},
block: {
width: 50,
height: 50,
backgroundColor: 'black'
}
});
export default App;
Run Code Online (Sandbox Code Playgroud)
这段代码有什么作用?它是一个大正方形,下面有一个按钮。当我点击按钮时,一个新的黑色方块 (50x50) 出现在大方块中。我通过创建一个新的数组元素(数组 = 块)来做到这一点。这是在函数CreateBlockHandler 中完成的。这不能正常工作!
函数MoveBlockHandler使小方块可移动。这有效!
什么不起作用?当我创建一个新的黑色方块时,黑色方块不会呈现在屏幕上。只有当我刷新时,才会呈现正方形。该方块是通过 CreateBlockHandler 创建的,因为当我在该函数中执行 console.log(blocks) 时,我可以看到添加了一个新的数组元素。
如何强制此代码对所有数组元素进行完全重新渲染?我试图将正方形的渲染包装在一个单独的函数(RenderBlocks)中,并且每次制作新正方形时我都会调用此函数(CreateBlockHandler 中的最后一行)。该函数被调用(我可以使用 console.log() 进行检查),但没有呈现任何方块。
当您分配blocks给array引用 gete 时,它会改变状态,因此它不会在setState.
const CreateBlockHandler = () => {
let array = [...blocks];
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1971 次 |
| 最近记录: |