gpt4 book ai didi

javascript - 如何修复 "Uncaught TypeError: Cannot read property ' value' of null”错误?

转载 作者:行者123 更新时间:2023-12-01 03:48:39 25 4
gpt4 key购买 nike

我想在 React 中设置一个简单的购物车。我正在尝试提供一个包含服装尺寸的下拉菜单。我在渲染中设置了它,但出了点问题,我得到:Uncaught TypeError: Cannot read property 'value' of null.

这是我的 JSX:

import React, { Component } from 'react';


let cart = {price:0,item:"",size:""}

export default class Cart extends Component {
handleClick(){
e => {
cart = {price:0,item:"userselection",size:"userselection"};
}
console.log(cart);
}

itemSelection(){
let userOrder = {price:0,item:"",size:""};
let userItem = "";
if (userItem == "pants1") {
let itemPrice = 20.00;
}

}


render() {
return (
<div className='Webshop' id='Webshop'>
<li>
<img src="./gods.jpeg" width="350" height="350"></img>
<button onClick={this.handleClick} id="addit">Add to cart</button>
<select id="size" onChange={this.change} value={this.state.value}>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="x-large">X-large</option>
</select>
<img src="./gods.jpeg" width="350" height="350"></img>
</li>
</div>
);
}
}

我的渲染返回 Null 值是否有问题?

编辑

由于这是由 Null 值引起的,我该如何修复此问题以获取下拉菜单?

最佳答案

原因是,您没有定义构造函数state变量,并且您正在访问this.state.value。首先定义状态,如下所示:

constructor(){
super();
this.state = {value: ''}
}

您以错误的方式使用箭头函数,请像这样使用它:

handleClick = (e) => {
cart = {price:0,item:"userselection",size:"userselection"};
console.log(cart);
}

您没有定义 change 方法,也定义一下。

像这样编写你的组件:

export default class Cart extends Component {
constructor(){
super();
this.state = {value: ''}
this.handleClick = this.handleClick.bind(this);
this.change = this.change.bind(this);
}

handleClick() {
cart = {price:0,item:"userselection",size:"userselection"};
console.log(cart);
}

change(e){
this.setState({value: e.target.value})
}

itemSelection(){
let userOrder = {price:0,item:"",size:""};
let userItem = "";
if (userItem == "pants1") {
let itemPrice = 20.00;
}
}


render() {
return (
<div className='Webshop' id='Webshop'>
<li>
<img src="./gods.jpeg" width="350" height="350"></img>
<button onClick={this.handleClick} id="addit">Add to cart</button>
<select id="size" onChange={this.change} value={this.state.value}>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="x-large">X-large</option>
</select>
<img src="./gods.jpeg" width="350" height="350"></img>
</li>
</div>
);
}
}

关于javascript - 如何修复 "Uncaught TypeError: Cannot read property ' value' of null”错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43383292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com