【发布时间】:2019-07-03 04:07:46
【问题描述】:
我正在尝试根据用户输入显示月份名称。我有一个名为 Constants js 文件的文件,其中我定义了我的月份数组。 情况1: 当用户在单击提交按钮时在文本字段中输入 4 时,它应该显示四月 案例2: 当用户输入 33 个月数时,它应该显示“无效的月份数”
Home JS file
<code>
import React, { Component } from 'react';
import constants from './Constants';
class Home extends React.Component{
constructor(props)
{
super(props);
this.state ={
value : ''
}
this.handleClick = this.handleClick.bind(this);
}
handleClick = (event) =>
{
this.setState({value: event.target.value})
}
render()
{
let newvalue = this.value;
let latestvalue = constants.MONTHS[newvalue] == null ? 'invalid month' : constants.MONTHS[newvalue] ;
return(
<div className='home'>
<h1>Welcome to my portfolio website</h1>
Enter Month number <input type="text" value={this.state.value}/>
<button type="button" onSubmit={this.handleClick()}> </button>
<p> Feel free to browse around and learn more about me.</p>
Month is {latestvalue}
</div>
);
}
}
export default Home;
</code>
Constants JS file
<code>
const constants = {
MONTHS: ['','Jan','Feb','Mar','April','May','June','July']
}
export default constants;
</code>
It should display month or invalid month
我收到此错误“TypeError: Cannot read property 'target' of undefined”
【问题讨论】:
-
我认为您的错误出现在
constants.MONTHS[newvalue] == null,因为数组的“无法找到”索引将返回undefined -
你可以用
let latestvalue = constants.MONTHS[newvalue] || 'invalid month'一枪搞定 -
我收到此错误,TypeError: Cannot read property 'target' of undefined
-
去掉括号
onSubmit={this.handleClick}。您正在调用 handleClick 方法,而不是附加它。 -
好的,去掉按钮上的onClick事件,在输入端添加
onChange={this.handleClick}。也许将handleClick更改为handleChange以进行澄清。
标签: javascript html reactjs react-redux frontend