简体   繁体   English

REACT NATIVE:如何获取 TextInput 的值和 Picker 的值

[英]REACT NATIVE: How to get value of TextInput and value of Picker

I want to get value of TextInput and Picker and insert it into my Flatlist .我想获取TextInputPicker的值并将其插入到我的Flatlist中。 The ways that i did i can just insert value of TextInput , but without Picker , or i did with Picker but couldnot get value of TextInput .我所做的方式我可以只插入TextInput的值,但没有Picker ,或者我使用Picker但无法获得TextInput的值。 Here is my code:这是我的代码:

These are UseState这些是 UseState

  const [selectedValue, setSelectedValue] = useState(' '); //for Picker
    const [text, setText] = useState(''); //for the TextInput
  <TextInput style={styles.input}
           placeholder="   Amount "
           keyboardType='numeric'
           onChangeText={text => setText(text)}
           value={text}
        />
  <Picker
              selectedValue={selectedValue}
              style={{ height: 50, width: 150 }}
              onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
               >  

              <Picker.Item label="Food" value="food" />
              <Picker.Item label="Transport" value="trans" />
                     </Picker>

Here is my Button and Flatlist code, the logic is that after pressing Button it insert into my Flatlist But I couldnot insert and the Value of Picker and value of TextInput```:这是我的 Button 和 Flatlist 代码,逻辑是按下 Button 后它插入到我的Flatlist但我无法插入Picker and value of TextInput 的值```:

 <Button
          title="Save"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
          onPress={() => {if ( selectedValue)  setData([...data, { name: selectedValue  }]) 
          console.log('sec'); }} /> //here i could insert value of Picker and instead of ```selectedValue``` i can put text i will get value of TextINput , how to get both of them?

        <FlatList
          data={data}
          renderItem={({ item }) => (<Text style = {styles.item}> {item.name}</Text>)}
          keyExtractor={(item, index) => index.toString()}  
           />

You forgot to add the value of textInput while adding the data to flatlist.您在将数据添加到平面列表时忘记添加 textInput 的值。

<Button
  title="Save"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
  onPress={() => {
    // You forgot to add the value of textInput to the data
    if (selectedValue && text) setData([...data, { name: selectedValue, textInput: text }]);
    console.log("sec");
  }}
/>
<FlatList
  data={data}
  renderItem={({ item }) => <React.Fragment>
    <Text style={styles.item}> {item.name}</Text>
    // Displaying the data of textInput
    <Text style={styles.item}>{item.textInput}</Text>
    </React.Fragment>}
  keyExtractor={(item, index) => index.toString()}
/>

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

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