我是新来的反应本地人,并且在设置新状态时遇到了一些麻烦。一切正常,直到出现第三个textinput为止,当我开始在其中输入文字时,计数器停留在1,应该停留在2,并且还要将textInputList更新为两个TextInput元素。我想了解为什么计数器没有变化,以及如何解决此问题:)
import React from 'react';
import { useState } from 'react';
import { Button, View, StyleSheet, TextInput } from 'react-native';
import colour from '../constants/Colors';
import StartButton from '../components/Buttons/BackToBackButton';
function ShowNames(props) {
return (
<View style={styles.lineContainer}>
<TextInput
style = {{ width: '70%', height: 40, borderColor: 'white', borderWidth: 2 }}
placeholder='Legg in navn her'
placeholderTextColor='white'
selectionColor='black'
onChangeText={props.handleTextChange}
/>
</View>
)
}
export default function BackToBack(props) {
const [nameList, setList] = useState([]);
const [counter, setCounter] = useState(0);
const [textInputList, setInputList] = useState(null)
const handleTextChange = (text, id) => {
tempList = nameList
tempList[id] = text
setList(tempList)
if (id == counter) {
setCounter(counter + 1)
AddNameInputs()
}
}
function AddNameInputs()
var tempList = [];
for (let i = 0; i < counter; i++) {
console.log('i: ' + i)
tempList.push(
<View style={styles.lineContainer} key={i+2}>
<TextInput
style={{ width: '70%', height: 40, borderColor: 'white', borderWidth: 2 }}
placeholder='Legg in navn her'
placeholderTextColor='white'
selectionColor='black'
onChangeText={(text) => handleTextChange(text, i+2)}
/>
</View>
)
}
setInputList(tempList)
}
return (
<View style={styles.container}>
<ShowNames handleTextChange={(text) => handleTextChange(text, 0)} />
<ShowNames handleTextChange={(text) => handleTextChange(text, 1)} />
{textInputList}
<StartButton title={"Start!"} height={100} />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colour.lightTurquoise,
alignItems: 'center',
justifyContent: 'flex-start',
paddingTop: 20,
paddingBottom: 20
// borderWidth: 4,
// borderColor: 'yellow'
},
lineContainer: {
flexDirection: 'row',
paddingBottom: 20
}
});
答案 0 :(得分:1)
我认为问题是此行tempList = nameList
。它会假定您在设置状态时引用的是同一对象,而不触发相关的更新。因此,最快的解决方法是仅使用tempList = [...nameList]
之类的传播算子克隆它?