gpt4 book ai didi

javascript - 无法在 react 中添加多个计数器

转载 作者:行者123 更新时间:2023-12-01 00:33:34 26 4
gpt4 key购买 nike

我想制作一个带有递增、递减和添加计数器按钮的计数器应用程序。但添加计数器功能不起作用。它显示此错误:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?

我已经尝试将其封装在标签中,但仍然不起作用。

import React,{Component} from 'react';
import './App.css';


export class App extends Component {
state={
count:0,
}

increment=()=>{
this.setState({ count: this.state.count + 1 });
}

decrement=()=>{
this.setState({ count: this.state.count - 1 });
}

addCounter=()=>{

<span><button onClick={this.increment}>+</button></span>

<span>{this.state.count}</span>
<span><button onClick={this.decrement}>-</button></span>


}

render() {
return (
<div className="App">


<button onClick={this.addCounter}>Add Counter</button>
</div>



)
}
}




export default App;

添加计数器函数应在前一个计数器下方添加另一个计数器。

最佳答案

基本上提取一个Counter组件。

然后让您的应用维护Counter组件列表。

// Counter Component
export class Counter extends React.Component {
state = {
count:0,
}

increment=()=>{
this.setState({ count: this.state.count + 1 });
}

decrement=()=>{
this.setState({ count: this.state.count - 1 });
}

render() {
return (
<div>
<span><button onClick={this.increment}>+</button></span>
<span>{this.state.count}</span>
<span><button onClick={this.decrement}>-</button></span>
</div>
);
}
}
// App Component
export class App extends React.Component {
state = {
counters: [], // additional state for Counter components
}

addCounter = () => {
this.setState({
counters: [
...this.state.counters,
Counter
]
})
}

render() {
return (
<div className="App">
<button onClick={this.addCounter}>Add Counter</button>
{ this.state.counters.map((Counter, index) => (
<Counter key={index} />)
)}
</div>
)
}
}

Demo

关于javascript - 无法在 react 中添加多个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58316652/

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