用于递增的构造函数问题(react Javascript) [英] Constructor Question (react Javascript) for incrementing
问题描述
如何在 React 组件中输入文本,该组件将显示一个带有提交按钮的文本框,旁边应该有一个数字,每次单击提交"时都会增加该数字.增量值(添加到计数器中)将是提交的每个单词的长度.
所以可以说我在文本框中写了嗨";(2 个字母)并单击提交 - 我的计数器应显示 2那么如果我在那里写欢迎"- 不是计数器会添加 7 ==>所以它会显示 9
本地状态应该在类组件内部.
谢谢:)
这是我得到的:
import React, { Component } from 'react'导出类 TextInput 扩展组件 {构造函数(){极好的()this.state = {计数:0}this.handleClick = this.handleClick.bind(this)}句柄点击(){this.setState(prevState => {返回 {计数:prevState.count + 1}})}使成为(){返回(<div><h1>{this.state.count}</h1><输入类型=文本"value={this.state.value} onChange={this.handleChange}/><button onClick = {this.handleClick}>更改</button>
)}}导出默认文本输入
您需要使用 value
状态并将其长度添加到 count
状态:
import React, { Component } from "react";导出类 TextInput 扩展组件 {状态 = {计数:0,值:",};handleClick = () =>{this.setState((prevState) => {返回 {计数:prevState.count + prevState.value.length,值:",};});};handleChange = (e) =>{this.setState({ value: e.target.value });};使成为() {返回 (<div><h1>{this.state.count}</h1><输入类型=文本"值={this.state.value}onChange={this.handleChange}/><button onClick={this.handleClick}>更改</button>
);}}导出默认文本输入;
how do i make a text input inside of a React component that will show a text box with a submit button , next to it there should be a number that will be incremented each time i click "submit". The increment value (that is added to the counter) will be the length of each word that was submitted.
so lets say i write in the text box "hi" (2 letters) and click submit - my counter should show 2 then if i write there "welcome" - not the counter will add 7 ==> so it will show 9
the local state should be inside of the class component.
Thanks :)
this is what i got :
import React, { Component } from 'react'
export class TextInput extends Component {
constructor(){
super()
this.state = {
count: 0
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
render(){
return(
<div>
<h1>{this.state.count}</h1>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button onClick = {this.handleClick}>Change</button>
</div>
)
}
}
export default TextInput
You need to use the value
state and add its length to the count
state:
import React, { Component } from "react";
export class TextInput extends Component {
state = {
count: 0,
value: "",
};
handleClick = () => {
this.setState((prevState) => {
return {
count: prevState.count + prevState.value.length,
value: "",
};
});
};
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
return (
<div>
<h1>{this.state.count}</h1>
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Change</button>
</div>
);
}
}
export default TextInput;
这篇关于用于递增的构造函数问题(react Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!