React 組件概括

React中一切皆可爲組件,組件從概念上類似於 JavaScript 函數,組件也可以理解爲React中的一種狀態機,它裏面包括從外面獲取的props 和內部保持狀態的state,並返回用於描述頁面展示內容的 React 元素,其中其數據是單向流動的。

一、組件的實現

    由於歷史版本的原因,React組件可以有多種實現方式:

    1.1 ES6 組件

      使用關鍵字class 來定義組件一般如下:      

class Hello extends React.Component {
    render() {
        return <div>hello world</div>;
    }
}

    1.2 ES5組件

    不使用class 關鍵字來定義組件,React提供了create-react-class 模塊:

var HelloMessage = React.createClass({
  render: function() {
       return <h1>Hello {this.props.name}</h1>;
  }
});

   1.3 純JS函數組件    

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

二、分類:

根據表單input等元素處理方式不同,可分爲受控組件,非受控組件。

2.1受控組件:

 “渲染表單的 React 組件還控制着用戶輸入過程中表單發生的操作”。input 表單元素的值是由 React 控制,當用戶將數據輸入到受控組件時,會觸發修改狀態的事件處理器,這時由你的代碼來決定此輸入是否有效(如果有效就使用更新後的值重新渲染)。如果不重新渲染,則表單元素將保持不變。

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('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

2.2 非受控組件:

表單數據將交由 DOM 節點來處理,可以使用 ref 來從 DOM 節點中獲取表單數據”。當用戶將數據輸入到表單字段(例如 input,dropdown 等)時,React 不需要做任何事情就可以映射更新後的信息。在非受控組件中,可以通過defaultValue 屬性爲表單元素設置默認值。

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 
             defaultValue="Bob"
             type="text" 
             ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

三、組件的生命週期:

每個組件都包含“生命週期方法”,可以重寫這些方法,以便於在運行過程中特定的階段執行這些方法。

生命週期圖譜:

資料‘生命週期圖譜’

四、組件間通信

組件內部狀態由state對象保存,組件之間傳值的方式簡單敘述下:,

    3.1 父子節點

    3.1.1父組件通過屬性向子組件傳值,子組件通過props屬性獲取:  

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;   // 獲取父組件APP傳入的props
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

     React對props規定,組件無論是使用函數聲明還是通過 class 聲明,都決不能修改自身的 props。   

 3.1.2  子組件向父組件傳值,通過由父組件傳入的子組件的callback函數。在子組件中觸發此callback,入參作爲更新傳遞的值。

  3.2 兄弟節點

當兄弟節點需要同步state時,一般是進行狀態提升。即將多個組件中需要共享的 state 向上移動到它們的最近共同父組件中,便可實現共享 state。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章