簡體   English   中英

示例代碼,錯誤:應為“;” 但發現“類”和更多語法錯誤

[英]Code from example, error: Expected “;” but found “class” and more syntax errors

在 React 新手中,我試圖從 Web 中理解示例。 你能告訴我那個代碼有什么問題嗎?

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"));

筆記:

  • 方法必須綁定到 class
  • 不要直接變異 state,使用 setState
  • 渲染必須有回報
  • 必須返回單個外包裝或使用片段
  • class 是反應中的類名
  • onclick 是 onClick 在反應
  • 不要直接注入body,創建一個root div

查看下面的工作代碼片段:

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM