【发布时间】:2021-10-05 15:49:54
【问题描述】:
所以,如果这是重复的,我很抱歉,但是我已经阅读了很多帖子并且找不到解决我的问题的方法,现在我在这里直接寻求帮助。
让我们解释一下这个问题,我的代码中有一个 Modal,它有一个 TextInput 和一个 Button。当 TextInput 中的文本发生更改并且单击 Button 时,我需要更新一个状态,我需要对文本做一些事情(但这对问题本身,所以让我们假设它是console.log)。如果我打开 Modal 并在 TextInput 中写一些东西,它会将文本保存在状态中,但是当我单击 Button 时它什么也不打印。但是当我关闭 Modal 并再次打开它时,如果我点击 Button 而不写任何内容,它会打印我之前写的内容。比如:
- 打开模态
- 在 TextInput 中写“Hello”
- 单击按钮。它什么也不打印
- 关闭模态
- 再次打开模态
- 单击按钮。它打印
Hello
我尝试了很多东西,但似乎都没有奏效,如果解释令人困惑,我很抱歉。
下面是一些示例代码:
function Example(){
const [modalVisibility, setModalVisibility] = useState(false)
const [text, setText] = useState()
return(
<SafeAreaView>
<Modal
transparent={true}
visible={modalVisibility}
onRequestClose={() => {
setModalVisibility(false)
}}>
<View>
<Button title="Close Modal" onPress={() => {
setModalVisibility(false)// closes the modal
}}/>
<TextInput
placeholder="Type..."
maxLenght={20}
onChangeText={(t) => {
setText(t) // updates the state in theory
}}
/>
<Button title="Click Me" onPress={() => {
console.log(text) // prints the state
}}/>
</View>
</Modal>
</SafeAreaView>
)
}
我尝试过的一些事情:
我尝试将onChangeText={...} 更改为异步函数并在setText(t) 中放置一个等待,但它不起作用。
我还尝试将onChangeText={...} 更改为onChange={e => setText(e.target.value)},但它返回了一个未定义的值
我在其他帖子中看到有人说要使用useEffect(() => {...}, [text]),但我不知道如何在我的情况下使用它。但是我在尝试这个时注意到的一件事是,如果我在 useEffect 内写一个 console.log(text) 并打印实际文本,但即使在那之后按钮仍然打印旧文本。
如果您能帮助我解决这种情况,我将非常感激和高兴。感谢阅读:)
【问题讨论】:
-
是
TextInput您的自定义组件吗? -
@nivendha 不,这不是自定义的,它是“react-native”的默认设置
-
我尝试了代码,对我来说工作正常。 snack.expo.dev/kDsgYNl5t
标签: javascript react-native expo state textinput