繁体   English   中英

React.js:将状态值直接分配给 TextField

[英]React.js: Assign value from state directly to TextField

我有一个获取交易详情的 axios 请求

getTransaction(batchRef) {
    return axios.post(`${API_BASE_URL_GET_OUTWARD_TRANSACTION}`, {
      batchRef: batchRef,
    });
  }

我通过这项服务调用它:

const [viewOutward, setViewOutward] = useState([]);

OutwardService.getTransaction(rowData.batchRef).then((response) => {
    setViewOutward(response.data);
});

它在 viewOutward 状态上正确设置为 json,例如 {reference: "2020091600", relatedReference: "2020091601}

现在,我想将这些值直接分配给文本字段

我是这样做的,我不确定在每个领域都使用地图是否是一个好习惯。

<TextField
                    variant="outlined"
                    margin="normal"
                    required
                    autoComplete="off"
                    fullWidth
                    type="text"
                    id="reference"
                    label="Reference"
                    value={viewOutward.map((viewOutward) => viewOutward.reference)}
                    onChange={(e) => setViewOutward(e.target.value)}
                    InputProps={{
                      classes: { input: classes.textfield1 },
                    }}
                    inputProps={{
                      maxLength: 16,
                    }}
                  />

它正在工作,但是它可能会影响性能吗?

有人可以建议仅使用一种状态在文本字段上设置这些值的正确方法。 谢谢你。

假设 API 响应:

[{reference: "2020091600", relatedReference: "2020091601"}, {reference: "2020091602", relatedReference: "2020091602"}, ...]

在 TextField 中使用状态

viewOutward.map((item, index) =>
  <TextField
        variant="outlined"
        margin = "normal"
        required
        autoComplete = "off"
        fullWidth
        type = "text"
        id = `${item.reference}` // if reference is unique
        label = "Reference"
        key = { index } // to identity unique for react 
        value = { item.reference } // assign value
        onChange = {(e) =>  //onchange of text assign new value to same object
                 setViewOutward(vo => 
                  vo.map(row => row.reference === item.reference
                  ? { ...row, reference: e.target.value //whatever property you can update 
                  } : row)
                 )
               }
        InputProps = {{
        classes: { input: classes.textfield1 },
      }}
        inputProps = {{
        maxLength: 16,
      }}
  />
)

添加有关如何更新对象数组状态的参考

暂无
暂无

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

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