In new to React, and I'm trying to understand examples from the Web. Could You tell me what is wrong with that code?
class MyComponent extends React.component {
constructor() {
this.state = {
counter: 0,
items: [1, 2]
};
}
increase(this) {
this.state.counter++;
}
addItem() {
this.state.items = this.state.items.push(this.state.items.length + 1);
}
render() {
<
div class = ”data” >
<
div > {
this.state.counter
} < /div> <
ul > {
this.state.items.map(item => ( <
li key = {
item
} > element {
item
} < /li>
))
} <
/ul> <
/div> <
div class = ”actions” >
<
button type = ”button” onclick = {
this.increase
} > zwiększ < /button> <
button type = ”button” onclick = {
this.addItem
} > dodaj < /button> <
/div>
}
} ReactDOM.render( < MyComponent >, document.querySelector("body"));
Notes:
Check out the working code snippet below:
class App extends React.Component { constructor(props) { super(props); this.state = { counter: 0, items: [1, 2] }; } //methods must bind to class increase = () => { //do not directly mutate state, use setState this.setState(state => ({ counter: state.counter + 1 })); }; //methods must bind to class addItem = () => { //do not directly mutate state, use setState this.setState(state => ({ items: [...state.items, state.items.length + 1] })); }; render() { //render must have a return //must return a single outer wrap or use fragment //class is className in react //onclick is onClick in react return ( < React.Fragment > < div className = "data" > < div > { this.state.counter } < /div> < ul > { this.state.items.map(item => ( < li key = { item } > element { item } < /li> )) } < /ul> < / div > < div className = "actions" > < button type = "button" onClick = { this.increase } > zwiększ < /button> < button type = "button" onClick = { this.addItem } > dodaj < /button> < / div > < /React.Fragment> ); } } //don't inject directly into body, create a root div ReactDOM.render( < App / >, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.