【问题标题】:How to Generate dynaimc UI on JSON response react-native如何在 JSON 响应 react-native 上生成动态 UI
【发布时间】:2019-07-15 01:02:58
【问题描述】:

// 这里我正在尝试生成动态 UI 。通过 API 我得到一些 JSON 格式的响应,我必须在 UI 上绘制它。就像我没有定义任何“TextInput”一样,它应该动态生成。下面是一些示例 JSON 响应。这可能会根据不同的请求而改变。 请帮忙,我卡在下面只是一个代码,我不知道该怎么做。

import * as React from 'react';
import { Text, View, StyleSheet, Alert, Picker } from 'react-native';
import { Constants } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';

var myloop = [];
export default class UiDynamic extends React.Component {

  // add a selectValue to your state to stop the overwriting
  state = {
    PickerValueHolder: [],
    selectedValue: ''
  }

  componentDidMount() {
    // remove the return 
   fetch('http://userapi/inventory/viewinventorytype', {  
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          "username" :"admin",
          "password" :"admin"
        })
      }).then((response) => response.json())
      .then((responseJson) => {
        // use the inventoryTypeData as it is already an array
        let PickerValueHolder = responseJson.inventoryTypeData;
        for (let i = 0; i < PickerValueHolder.length; i++) {
            datavalue=() => {
                <Text>Hello ABhi</Text>
                console.log("Hello ABhi");   
            }
        }

        this.setState({ PickerValueHolder }); // Set the new state
      })
      .catch((error) => {
        console.error(error);
      });
    }

  GetPickerSelectedItemValue=()=>{
    Alert.alert(this.state.PickerValueHolder);
  }

  render() {


    for (let i = 0; i < 10; i++) {
        datavalue=() => {
            <Text>Hello ABhi</Text>
            console.log("Hello ABhi");   
        }
      myloop.push(
        <View key={<TextInput></TextInput>}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{<Text>Hello</Text>}</Text>
        </View>
      );
    }


    return (
      <View style={styles.container}>
      {this.datavalue.bind(this)}
      {myloop}

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

// 下面是示例 JSON 响应 .. 假设这里有四个属性及其数据类型,所以在 UI 4 上应该生成“TextInput”。

{
  "inventoryTypeData": [{
    "data type": int,
    "Field 1": ""
  }, {
    "data type": string,
    "Field2": ""
  }, {
    "data type": int,
    "Field 3": ""
  }, {
    "datatype": int,
    "Field4": ""
  }],
  "success": "true"
}

【问题讨论】:

    标签: javascript ajax reactjs react-native react-redux


    【解决方案1】:

    import { TextInput } from 'react-native';

    一旦您将响应映射到状态 this.setState({ PickerValueHolder });

    然后你可以在你的渲染方法中使用 map 函数循环遍历它

      return(
        <View style={styles.container}>
          {this.state.PickerValueHolder.map(data=>(
            <View>
              <TextInput
                placeholder={data.placeholder}
                keyboardType={data.datatype==="int" ? 'numeric': 'default'}
                onChangeText={(text) => this.setState({...this.state.value [data.name]: text })}
                value={this.state.value[data.name]}
              />
              <Button
                onPress={this.handleButtonPress(data.name).bind(this)}
              />
            <View/>
          />
          ))}
        </View>
      )
    }```
    
    So here you are checking if the datatype is an int and then setting the keyboard type to numeric
    
    This is also setting all the changes to a value object in state.
    
    The Button calls a function with the name of of the value related to the text input
    

    【讨论】:

    • 谢谢..我将如何放置占位符的一件事是响应按钮我还必须生成一个按钮
    • 所以你想把它映射到一个TextInput,数据作为占位符和一个按钮来提交任何更改?
    • 基本上在重新运行功能中我没有写任何文本输入或按钮或文本,一旦我打开应用程序,我会在某个时候从服务器获得响应 4 响应然后我必须绘制 4 个字段,如果 10 然后 10 个字段包括占位符、数据类型和按钮、选择器文本输入,取决于 JSON 响应
    • 我认为这些更改符合您的要求?
    • 感谢宝贵的时间,我也试试看,但是有没有可能在从 API 获得 JSON 格式的响应后,我们可以绘制动态 UI,比如如果在 JSON 中获得 5 个属性,然后是 5 个 Textinput或者如果得到 10 那么 10 textinput 。我需要一些帮助和指导
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多