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

标签 javascript react-native

如何通过单击按钮在 React Native 中添加文本输入?例如,我会按“+”按钮,它会在 View 底部添加文本输入。

这是我在另一个页面中找到的代码,但是当我点击加号时什么也没有发生

var textInput = []

let addTextInput = (key) => {
    textInput.push(<TextInput key={key} style={{color:'red',borderColor:'red'}}/>);
    { textInput }
}

let orgServiceandWorkHours = (
    <View>
        <Button title='+' onPress={() => 
       addTextInput(textInput.length)} />
    {textInput.map((value, index) => {
      return value
    })}
    </View>
)

最佳答案

这是一个完整的示例 ( https://snack.expo.dev/@heytony01/mature-carrot ) 和下面的代码。

export default function App() {

  const [numTextInputs,setNumTextInputs] = React.useState(0);
  return (
    <View style={styles.parent}>
        {/* Button */}
        <TouchableOpacity onPress={()=>setNumTextInputs(val=>val+1)} style={styles.buttton}>
              <Text style={styles.text}> Add TextInput </Text>
        </TouchableOpacity>
        <ScrollView style={{flex:1}} >
              {[...Array(numTextInputs).keys()].map(key=>{
                return <TextInput key={key} placeholder="Here Man" style={{width:200,height:100,borderColor:"blue",margin:10,borderWidth:1}}/>
              })}
        </ScrollView>
    </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"},
})

关于javascript - 如何在 React Native 中动态添加或删除文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70325989/

相关文章:

javascript - [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client

javascript - 相机 child 没有出现

ios - 将原生 iOS 应用程序的数据迁移到 React Native 应用程序的异步存储

javascript - Flow - 来自 react-native/Libraries 的错误

javascript - 如何通过对象传递回调的结果?

javascript - cordova使用什么js 'engine'?

android - 如何解决使用 react-native 构建 APK 时无法执行 aapt 的错误?

android - 如何在 react-native 中获取子组件的引用?

ios - React Native 无效的 podfile "No such file or directory - ./node_modules/.bin/react-native."

javascript - 如何创建动态表单?