繁体   English   中英

如何在 React Native 中动态添加或删除文本输入

[英]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.

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