1. 程式人生 > >【一起來學React】- 基礎知識

【一起來學React】- 基礎知識

說一千道一萬,不如直接動手,你是否還在為學習react看官方文件而煩惱呢?和我一起來動手,從實踐中領悟理論吧!
ps:本系列文章只適合新手(但是不適合沒有js基礎的尤其是this指向問題,這玩意不搞清楚,基本學不會)
本文為系列文章首發於我的部落格:https://www.fakin.cn

安裝React

這個就不說了,太簡單了

npm install -g create-react-app
create-react-app my-app
cd my-app
npm start

JSX

React使用JSX來替代JavaScript。看起來很像XML的JavaScript 語法擴充套件。

const fakin = <h1>fakin</h1>

反正你得記住,JSX在React中到處都是(當然你也不使用JSX,甚至你可以不用ES6呢,但是JSX和ES6更加方便)。

元件

三大框架中元件都是很關鍵的,React和Vue不一樣,Vue有.vue檔案作為元件,而React由函式或者類定義元件的,如下所示:

function Fakin(props) {
  return <h1>fakin</h1>
}

或者

class Fakin extends React.Component {
  render() {
    return <h1>fakin</h1>
  }
}

State

狀態,通過this.state定義(其實我個人覺得叫資料好點)

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
        }
    }
    //xxxx
}

嗨呀,難受,就是你可以通過this.state來修改render渲染的資料。這時候你可能會問render又是啥,問的好!

render() {
	return return (<div id="box"
></div>) }

簡單todoList

如果你有一定的js基礎,或者說其他mvvm框架的基礎,那麼這些東西都挺簡單的,那麼咱們就來動手實現一個簡單todoList吧!

import React, {Component} from 'react';
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            inputValue: ''
        }
    }
    handleBtnClick() {
        if (!this.state.inputValue) {
            return
        }
        this.setState({
            list: [...this.state.list, this.state.inputValue],
            inputValue: ''
        })
    }
    handleChange(event) {
        this.setState({
            inputValue: event.target.value
        })
    }
    handleItemClick(index) {
        let list = [...this.state.list];
        list.splice(index, 1);
        this.setState({
            list
        })
    }
    render() {
        return (
            <div id="box">
                <input onChange={this.handleChange.bind(this)} value={this.state.inputValue} className="input"/>
                <button onClick={this.handleBtnClick.bind(this)} className="btn">add</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return <li key={index}>{item}
                                <button onClick={this.handleItemClick.bind(this, index)} className="btnDel">X</button>
                            </li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default App;

第一章到此就結束了,其實react上手還是很簡單的,下一章咱們來說說react中元件的生命週期!