React从输入字段读取JSON元素值返回undefined的解决办法
问题原因
从输入字段获取的myJSON是JSON格式的字符串,不是JavaScript对象。直接对字符串调用.name属性自然返回undefined——因为字符串本身没有name这个属性;而从JS文件导入的内容,是被打包工具自动解析后的JS对象,所以能直接访问.name。
解决方法
用JSON.parse()方法把JSON字符串转换成JavaScript对象,同时建议加上异常处理,避免输入无效JSON导致页面报错。
修改后的代码示例
import './App.css'; import JSONObject from './aa_DDFFormConfigJSON' function App() { function ConfigJSONReady(event) { // 获取输入框的JSON字符串 const jsonString = document.getElementsByName("myJSONField")[0].value; try { // 解析字符串为可操作的JS对象 const myJSON = JSON.parse(jsonString); console.log("myJSON.name using input field: " + myJSON.name); } catch (error) { // 捕获并处理JSON格式错误 console.error("输入的JSON格式无效:", error); } // 导入的对象可直接使用 console.log("myJSON.name using file import: " + JSONObject.name); } return ( <div> <header> Everything here is in a REACT App <p>Success!!</p> </header> <form> <textarea rows="10" cols="200" maxlength="5000" id='myJSONField' defaultValue='{"name": "This is the name field"}'> </textarea> <input name="DDFConfigJSONReady" id="DDFConfigJSONReady" type="checkbox" onChange={ConfigJSONReady} /> </form> </div> ); } export default App;
额外优化(React推荐写法)
在React中更建议用**状态(state)**管理输入值,替代直接操作DOM,更符合React数据流理念:
import './App.css'; import { useState } from 'react'; import JSONObject from './aa_DDFFormConfigJSON' function App() { const [jsonInput, setJsonInput] = useState('{"name": "This is the name field"}'); function ConfigJSONReady(event) { try { const myJSON = JSON.parse(jsonInput); console.log("myJSON.name using input field: " + myJSON.name); } catch (error) { console.error("输入的JSON格式无效:", error); } console.log("myJSON.name using file import: " + JSONObject.name); } return ( <div> <header> Everything here is in a REACT App <p>Success!!</p> </header> <form> <textarea rows="10" cols="200" maxlength="5000" id='myJSONField' value={jsonInput} onChange={(e) => setJsonInput(e.target.value)}> </textarea> <input name="DDFConfigJSONReady" id="DDFConfigJSONReady" type="checkbox" onChange={ConfigJSONReady} /> </form> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者CheeseNWine
相关产品推荐
相关产品推荐

