![](/img/trans.png)
[英]how to fix the Uncaught TypeError: Cannot read property 'Value' of null
[英]How to Fix “Uncaught TypeError: Cannot read property 'value' of null” error?
我想在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值引起的,如何解决此问题以获得下拉菜单?
原因是,您没有定义constructor
和state
变量,并且正在访问this.state.value
。 首先定义这样的state
:
constructor(){
super();
this.state = {value: ''}
}
您使用arrow function
的方式有误,请像这样使用它:
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>
);
}
}
select
元素正在请求this.state.value
。 似乎this.state
为null
,因此在尝试访问null.value
时会看到该错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.