简体   繁体   English

React Native - 动态创建新组件 onPress

[英]React Native - dynamically create new component onPress

I'm looking to dynamically create a new component every time the user clicks a button.每次用户单击按钮时,我都希望动态创建一个新组件。

 export default function WorkoutCard({ children }) { const [workoutNum, setWorkoutNum] = useState([1]); const addSets = () => { setWorkoutNum(workoutNum.push(workoutNum.length + 1)); }; return ( <View style={styles.card}> <AppText style={styles.exerciseHeader}>{children}</AppText> {workoutNum.map((num) => ( <WorkoutTextInput workoutNum={num} /> ))} <Divider></Divider> <Button title="Add set" style={styles.add} onPress={addSets} /> </View> ); }

Basically, I'm trying to create an array which is also going to have the following values [1,2,3,4...] when the user clicks the button.基本上,我正在尝试创建一个数组,当用户单击按钮时,该数组也将具有以下值 [1,2,3,4...]。 But I'm getting the following error when I press the button - 'Undefined is not a function'.但是当我按下按钮时出现以下错误 - “未定义不是函数”。

Any tips on how I can fix this please?请问有什么提示可以解决这个问题吗?

Problem: push()问题:推()

The problem is the method Array.push() .问题是方法Array.push() The method mutates the array and returns the length of the new array.该方法改变数组并返回新数组的长度。 It does not return the array itself.它不返回数组本身。

setWorkoutNum(workoutNum.push(workoutNum.length + 1));

When you call this, you are changing your state from an array [1] to a number 2 .当您调用它时,您正在将 state 从array [1]更改为number 2

Solution: concat() or spread解决方案:concat() 或 spread

You need to set your state to a new array.您需要将 state 设置为新阵列。 You can do this with spread notation [...state, newVal] or with Array.concat() .您可以使用扩展符号[...state, newVal]或使用Array.concat()来做到这一点。 The concat method creates a new array and does not mutate the existing one. concat 方法创建一个新数组并且不会改变现有数组。

setWorkoutNum(workoutNum.concat(workoutNum.length + 1));
setWorkoutNum([...workoutNum, workoutNum.length + 1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM