[英]Problem getting a Javascript dynamic Object property value
我正在運行 React Material-UI 自動完成組件,並且正在努力讀取 handleSelect function 中的 Javascript Object 屬性。
我可以獲得 townname 值,盡管這不是 React 方式:
var selectedValue = document.getElementById('combo-box-demo').value;
我在嘗試獲取 Javascript Object 的相應 townid 屬性值時遇到問題。
我覺得我已經嘗試了所有明顯的東西,例如 Object.property 和 Object["property"],但沒有一個會編譯......它們都給出了 TypeError: Cannot convert undefined or null to object。
但是,我在谷歌瀏覽器控制台window可以看到數據。
誰能提出解決方案? 提前謝謝了。
我的代碼:
[/* eslint-disable no-use-before-define */
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import axios from 'axios'; // Asynchronous communication with Server
export default function Autocomplete_ComboBoxDemo(props) {
var url_orig = props.data.url;
const loading = true;
const \[responseData, setResponseData\] = React.useState(\[\]);
var data = \[\];
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
} // if
}) // React.useEffect()
const handleChange = (event) => {
// Replace <event.target.value>
var url = url_orig.replace("<event.target.value>", event.target.value)
axios.get(url)
.then((response) => {
data = response.data.data\[props.data.userSelectedValue\]; // OK
setResponseData(data)
}) // .then((response)
}
const handleSelect = (event) => {
console.log("Entered handleSelect")
var selectedValue = document.getElementById('combo-box-demo').value;
console.log("selectedValue=", selectedValue)
console.log("responseData=", responseData)
var dataIndex = responseData.findIndex(x => x.townname === selectedValue);
console.log("dataIndex=", dataIndex)
var selectedID = responseData\[dataIndex\];
console.log("selectedID=", selectedID)
console.log("typeof(selectedID)=", typeof(selectedID))
console.log("responseData\[dataIndex\]=", responseData\[dataIndex\])
}
return (
<Autocomplete
id="combo-box-demo"
options={responseData}
getOptionLabel={(responseData) => responseData\[props.data.userSelectedValue\]}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label={props.data.TextFieldlabel} onChange={handleChange} onSelect={handleSelect}/>
}
/>
);
}][1]
使用 onChange 道具並在其中設置一個方法,您將獲得 val 參數中的值
<Autocomplete
id="combo-box-demo"
options={responseData}
onChange={(e, val) => updateValue(e, val)}
getOptionLabel={(responseData) => responseData\[props.data.userSelectedValue\]}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label={props.data.TextFieldlabel} onChange={handleChange} onSelect={handleSelect}/>
}
/>
聲明一個方法
const updateValue=(e, val)=>{
console.log(e.taget.value);
console.log(val);
}
在第一個控制台結果中,你得到一個 label,在第二個控制台中你得到你想要的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.