一小時入門React

1.基本語法(jsx)

const name="小明";
const getName = () => {
    return "小明"
}
const element = <h1>Hello, world!</h1>;
// 嵌入變量
const element = <h1>Hello, {name}</h1>;
// 嵌入表達式
const element = <h1>Hello, {getName()}</h1>;
複製代碼

注意:在點擊事件中,不要直接調用函數,若是須要傳遞參數,使用箭頭函數,jsx中全部dom事件必須用駝峯命名。以下:html

const a = <a onClick={() => this.handleClick(params)}>點擊</a>
複製代碼

1.1. 條件渲染

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />; } return <GuestGreeting />; } 複製代碼

1.2. 循環渲染

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);
複製代碼

2.組件

react中全部的東西都是組件,從定義類型組件分爲函數式組件class組件兩種,從功能上區分又有容器組件和ui組件,根據表單相關又能夠分爲受控組件非受控組件,更高級的組件用法還有高階組件等。react

react時單向數據流,數據只能從父組件傳遞給子組件,子組件經過props參數獲取父組件傳遞的內容。web

2.1.函數式組件

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
複製代碼

2.2.class組件

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div>
    );
  }
}

ReactDOM.render(
  <Clock />, document.getElementById('root') ); 複製代碼

2.3.容器組件

負責處理業務邏輯redux

//容器組件
class TodoListContainer extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            todos:[]
        }
        this.fetchData = this.fetchData.bind(this);
    }
    componentDidMount(){
        this.fetchData();
    }
    fetchData(){
        fetch('/api/todos').then(data =>{
            this.setState({
                todos:data
            })
        })
    }
    render(){
        return (
            <div> <TodoList todos={this.state.todos} /> </div> ) } } 複製代碼

2.4.UI組件

只負責展現後端

//展現組件
class TodoList extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        const {todos} = this.props;
        return (
            <div> <ul> {todos.map((item,index)=>{ return <li key={item.id}>{item.name}</li> })} </ul> </div>
        )
    }
複製代碼

2.5.受控組件

React 的 state 爲「惟一數據源」。渲染表單的 React 組件還控制着用戶輸入過程當中表單發生的操做。被 React 以這種方式控制取值的表單輸入元素就叫作「受控組件」。api

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('提交的名字: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          名字:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="提交" />
      </form>
    );
  }
}
複製代碼

2.6.非受控組件

表單數據將交由 DOM 節點來處理服務器

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
複製代碼

2.7.高階組件

高階組件主要用來處理組件直接按可複用的邏輯,將可複用的部分抽離出來,供其他組件使用。react-router

高階組件是參數爲組件,返回值爲新組件的函數app

const EnhancedComponent = higherOrderComponent(WrappedComponent);
複製代碼

詳情請參考react官網 高階組件教程dom

3.組件生命週期

3.1.掛載

當組件實例被建立並插入 DOM 中時,其生命週期調用順序以下:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount() ---一般在今生命週期獲取後端數據

3.2.更新

當組件的 props 或 state 發生變化時會觸發更新。組件更新的生命週期調用順序以下:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate() ---經常使用於代碼優化
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

3.3.圖解

4.setState詳解

setState() 將對組件 state 的更改排入隊列,並通知 React 須要使用更新後的 state 從新渲染此組件及其子組件。這是用於更新用戶界面以響應事件處理器和處理服務器數據的主要方式。

4.1. 基本用法和參數

setState有兩個參數,第一個是要更新的內容,能夠是對象或者函數,第二個參數是回調函數更新完成後的操做能夠寫在回調函數中。

1)第一參數爲對象

this.setState({quantity: 2})
複製代碼

2)第一參數爲函數

this.setState((state, props) => {
  return {counter: state.counter + props.step};
});
複製代碼

setState() 的第二個參數爲可選的回調函數,它將在 setState 完成合並並從新渲染組件後執行。一般,咱們建議使用 componentDidUpdate() 來代替此方式。

4.2 setState()執行後發生了什麼?

  • static getDerivedStateFromProps()
  • shouldComponentUpdate() ---返回true則繼續往下執行,返回false將不繼續執行
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

5.路由基礎

react-router官網

react路由升級到v4版本以後(目前已經到v5),路由直接集成到DOM結構中,最經常使用的路由組件有:

// 至關於a標籤的功能
 <Link to="/">Home</Link>
 
 // 路由容器,傳入組件後,匹配到路由就會渲染對應組件
 <Route exact path="/" component={Home} />
 <Redirect to="/somewhere/else" />
 
 // 單頁應用路由組件要包含整個項目最大的容器
 <Router>
  <App />
 </Router>
 
 // 使用switch將Route或者Redirect包起來以後,智慧渲染第一個匹配路由的組件
 <Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
 </Switch>

複製代碼

關於每一個路與組件詳細的api介紹,請參考react-router官網

  1. React周邊
相關文章
相關標籤/搜索