#react-native
#react-native
Вопрос:
почему автоматическое обновление useState? Я нажму кнопку и не буду показывать ввод текста. но я могу сохранить файл без изменений. будет отображаться textinput. извините за мой плохой английский
импортируйте React, {useState, useEffect} из ‘react’; импортируйте {Text, TextInput, View, Button,} из ‘react-native’;
const Test = ({navigation}) => {
const [textInput, settextInput] = useState([]);
useEffect(() => {
addTextInput = (key) => {
textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
settextInput(textInput);
console.log(textInput);
}
},[textInput]);
return(
<View>
<Button title=' ' onPress={() =>
addTextInput(textInput.length)} />
{textInput.map((value, index) => {
return value
})}
<Text>{textInput.length}</Text>
</View>
);
}
export default Test;
Ответ №1:
У меня есть несколько предложений, чтобы улучшить ваш код.
-
Не меняйте значение состояния, если не используется ‘setState’. Это неверно по своей природе и вызывает ошибки.
addTextInput = (key) => { textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]); settextInput(textInput); console.log(textInput); }
-
Состояние просто содержит значение, оно не должно содержать разных вещей. Вы должны вернуть TextInput в вашей функции map.
-
Я пытаюсь переписать ваш код, извините, потому что мой английский. Надеюсь, вам поможет
код:
const [textInput, setTextInput] = React.useState(['1', '2'])
const addTextInput = (key: string) => {
const tempInput = textInput.concat([key])
setTextInput(tempInput)
}
return (
<View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
<Button title=" " onPress={() => addTextInput(textInput.length.toString())} />
{textInput.map((value, index) => {
return (
<TextInput style={{ backgroundColor: '#7ACB4A', marginTop: 10, width: '70%' }} key={index ''} />
)
})}
<Text>{textInput.length}</Text>
</View>
)
}