[英]How to dynamically add or remove a Text Input in React Native
如何通過單擊按鈕在 React Native 中添加文本輸入? 例如,我會按下“+”按鈕,它會在視圖底部添加一個文本輸入。
這是我在另一個頁面中找到的代碼,但是當我點擊加號時沒有任何反應
var textInput = []
addTextInput = (key) => {
textInput.push(<TextInput key={key} />);
this.setState({ textInput })
}
let orgServiceandWorkHours = (
<View>
<Button title='+' onPress={() =>
addTextInput(textInput.length)} />
{textInput.map((value, index) => {
return value
})}
</View>
)
你可以簡單地使用 react 鈎子useState
和條件渲染showTextInput && <View/>
來做到這一點。 只有當 showTextInput 為 true 時才會顯示視圖。 這是一個完整的示例( https://snack.expo.dev/@heytony01/mature-carrot )和下面的代碼。
export default function App() {
// showTextInput value
const [showTextInput,setShowTextInput] = React.useState(false);
// Function to switch between true and false
const onPress = ()=>{
setShowTextInput(pastVal=>!pastVal)
}
return (
<View style={styles.parent}>
{/* TextInput */}
{showTextInput&&<TextInput placeholder="Enter name" style={styles.textInput}/>}
{/* Button */}
<TouchableOpacity onPress={onPress} style={styles.buttton}>
<Text style={styles.text}> {!showTextInput?"Show TextInput":"Hide TextInput"} </Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
parent:{flex:1,justifyContent:"center",alignItems:"center"},
textInput:{width:"80%",height:"5%",backgroundColor:"lightgray",margin:20,borderRadius:10,textAlign:"center"},
buttton:{width:"80%",height:"12%",backgroundColor:"lightblue",borderRadius:10,
justifyContent:"center",alignItems:"center"
},
text:{fontSize:30,fontFamily:"bold",color:"black"},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.