简体   繁体   English

我怎样才能在本机反应中获得这个输入的值?

[英]how can i get the value of this inputs in react native?

so i cannot manage to get the value of any of my inputs, and the only thing is working for me is grabbing them inside render but just getting letter by letter.所以我无法获得任何输入的价值,唯一对我有用的是在渲染中抓取它们,但只是逐个字母地获取。 I want to use the same state for all of them (formData) so when I submit I can grab all the values in an unique object我想对所有这些 (formData) 使用相同的状态,所以当我提交时,我可以获取唯一对象中的所有值

Any recommendation to solve it??有什么建议可以解决吗??

export default class TimeOff extends Component {
constructor(props) {
    super(props);
    this.state = {
      selectedStartDate: null,
      selectedEndDate: null,
      selectedValue: '',
      formData: '',
    };
  }

  handleSubmit = event =>  {
    event.preventDefault()
    console.log(this.state.formData)

      render(){
    Moment.locale('en')
    const { selectedStartDate, selectedEndDate, formData, selectedValue } = this.state;
    const minDate = new Date();
    const maxDate = new Date(2090, 1, 1);
    const startDate  =  selectedStartDate ? selectedStartDate.toString() : '';
    const endDate = selectedEndDate ? selectedEndDate.toString() : '';

    return(
    <ScrollView showsVerticalScrollIndicator={false}>
        <Navbar />
        <Text style={styles.hOneTimeOff}>Schedule time off</Text>
        <View style={styles.timeOffWrapper}>
            <TextInput
                name="firstname"
                style={styles.timeOffInput}
                mode='outlined'
                placeholder="First name"
                value={formData.firstname}
                onChangeText={firstname => this.setState({formData: firstname})}
            />
            <TextInput
                name="lastname"
                style={styles.timeOffInput}
                mode='outlined'
                placeholder="Last name"
                value={formData.lastname}
                onChangeText={lastname => this.setState({formData: lastname})}
            />
            <Picker 
            name="role"
            style={styles.timeOffPicker} 
            value={formData.role}
            selectedValue={selectedValue}
            onValueChange={role => this.handlePicker(role)}
            >
                <Picker.Item label="What's your role?" value=''/>
                <Picker.Item label='Warehouse' value='Warehouse'/>
                <Picker.Item label='Bakery' value='Bakery'/>
                <Picker.Item label='Dry pack' value='Dry pack'/>
                <Picker.Item label='Dry mix' value='Dry mix'/>
                <Picker.Item label='Maintenance' value='Maintenance'/>
                <Picker.Item label='Mechanical' value='Mechanical'/>
            </Picker>
            <View style={styles.container}>
                <CalendarPicker
                    startFromMonday={true}
                    allowRangeSelection={true}
                    minDate={minDate}
                    maxDate={maxDate}
                    selectedDayColor="#00486D"
                    selectedDayTextColor="#FFFFFF"
                />
                <View>
                    <Text>Start Date: {Moment(startDate).format("M/D/YYYY")}</Text>
                    <Text>End Date: {Moment(endDate).format("M/D/YYYY")}</Text>
                </View>
            </View>
            <TouchableOpacity style={styles.btnTimeOff} onPress={this.handleSubmit}>
                <Text style={styles.btnTextTimeOff}>Submit</Text>
            </TouchableOpacity>
        </View>
    </ScrollView>
    )
}

} }

Your on change function is always overwriting your entire previous state.您的 on change 功能总是会覆盖您之前的整个状态。

You can use the setState function with a callback and the spread operator to update the state without losing previous state like so:您可以使用带有回调和扩展运算符的 setState 函数来更新状态而不会丢失以前的状态,如下所示:

  1. First create and function for onTextChange:首先为 onTextChange 创建和运行:
const handleChange = (name, value) => {
    this.setState(
        (previousState) => {
            let previousFormData = previousState.formData;
            return {
                ...previousState,
                formData: {
                    ...previousFormData,
                    [name]: value
                }
            }
        }
    )
}
  1. Then Update you component like so:然后像这样更新你的组件:
export default class TimeOff extends Component {
constructor(props) {
    super(props);
    this.state = {
      selectedStartDate: null,
      selectedEndDate: null,
      selectedValue: '',
      formData: '',
    };
  }

  handleSubmit = event =>  {
    event.preventDefault()
    console.log(this.state.formData)
  }

    handleChange = (name, value) => {
        this.setState(
            (previousState) => {
                let previousFormData = previousState.formData;
                return {
                    ...previousState,
                    formData: {
                        ...previousFormData,
                        [name]: value
                    }
                }
            }
        )
    }
    render(){
    Moment.locale('en')
    const { selectedStartDate, selectedEndDate, formData, selectedValue } = this.state;
    const minDate = new Date();
    const maxDate = new Date(2090, 1, 1);
    const startDate  =  selectedStartDate ? selectedStartDate.toString() : '';
    const endDate = selectedEndDate ? selectedEndDate.toString() : '';

    return(
    <ScrollView showsVerticalScrollIndicator={false}>
        <Navbar />
        <Text style={styles.hOneTimeOff}>Schedule time off</Text>
        <View style={styles.timeOffWrapper}>
            <TextInput
                name="firstname"
                style={styles.timeOffInput}
                mode='outlined'
                placeholder="First name"
                value={formData.firstname}
                onChangeText={text => this.handleChange("firstname", text)}
            />
            <TextInput
                name="lastname"
                style={styles.timeOffInput}
                mode='outlined'
                placeholder="Last name"
                value={formData.lastname}
                onChangeText={text => this.handleChange("lastname", text)}
            />
            <Picker 
            name="role"
            style={styles.timeOffPicker} 
            value={formData.role}
            selectedValue={selectedValue}
            onValueChange={role => this.handlePicker(role)}
            >
                <Picker.Item label="What's your role?" value=''/>
                <Picker.Item label='Warehouse' value='Warehouse'/>
                <Picker.Item label='Bakery' value='Bakery'/>
                <Picker.Item label='Dry pack' value='Dry pack'/>
                <Picker.Item label='Dry mix' value='Dry mix'/>
                <Picker.Item label='Maintenance' value='Maintenance'/>
                <Picker.Item label='Mechanical' value='Mechanical'/>
            </Picker>
            <View style={styles.container}>
                <CalendarPicker
                    startFromMonday={true}
                    allowRangeSelection={true}
                    minDate={minDate}
                    maxDate={maxDate}
                    selectedDayColor="#00486D"
                    selectedDayTextColor="#FFFFFF"
                />
                <View>
                    <Text>Start Date: {Moment(startDate).format("M/D/YYYY")}</Text>
                    <Text>End Date: {Moment(endDate).format("M/D/YYYY")}</Text>
                </View>
            </View>
            <TouchableOpacity style={styles.btnTimeOff} onPress={this.handleSubmit}>
                <Text style={styles.btnTextTimeOff}>Submit</Text>
            </TouchableOpacity>
        </View>
    </ScrollView>
    )
}

This also preserves the other variables in your state object.这也保留了状态对象中的其他变量。

You keep overwriting the "formData" state value.您不断覆盖“formData”状态值。

Since you want it to act as an object (with entries: "firstname", "Lastname", etc) when you setState you should wrap the entries with curly brackets like this:由于您希望它在 setState 时充当对象(带有条目:“firstname”、“Lastname”等),因此您应该用大括号将条目包裹起来,如下所示:

...
onChangeText={firstname => this.setState({formData: {firstname}})}
...
onChangeText={lastname=> this.setState({formData: {lastname}})}
...
onChangeText={firstname => this.setState({formData: {...this.state.formData, firstname}})}

onChangeText={lastname=> this.setState({formData: {...this.state.formData, lastname}})}

Use this to update the nested state object, it will keep old values and would also update new one使用它来更新嵌套的状态对象,它将保留旧值并更新新值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native:我如何获取 Picker 的值并将其添加到 Flatlist - React Native: how can i Get value of Picker and add it to Flatlist 如何获得 react-native 中的当前 y 值? - how can i get current y value in react-native? 我如何从 React Native 中的动画或插值中获取值? - How can I get the value from an animated or interpolated value in React Native? 如何通过增加输入ID来获取输入值? - How can I get input value by increasing inputs id? 如何在 react-native 中获取 refScrollView.current 值? - how can i get refScrollView.current value in react-native? 如何将 TextInput 的值存储到本地存储并在应用程序以本机反应启动时获取它们? - How can I store the value of TextInput to local storage and get them when the app starts in react native? 如何获取已选中(复选框)的值并在本机反应中自动完成 textInput - How can I get the value of checked (checkbox) and autocomplete a textInput in react native React Native-如何添加10个文本输入并获取总计 - React native - How to add 10 text inputs and get the total 为什么 useState 有这种行为,以及如何在我设置值的同一函数中获取更新值? 在反应原生 - why useState have this behavier and how I can get updated value in in same function where I set value? In react-native 如何在反应原生中从数组中找到特定值 - How can I find particular value from array in react native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM