iT邦幫忙

1

React 學習筆記_8 (Thinking in React - 4 )

第五步:加入相反的資料流

  • 目前已經建立了由上往下傳遞的props與state,但需要加入反向的資料流。
  • 為了確保當使用者改變表格內容後就會更新state已反映使用者輸入的內容,在input上使用onChange(元件內的值發生改變)來接收event,event發生後會呼叫setState來更新state,並將更新後的state再次傳遞給子層並渲染到html中

流程圖 :
https://ithelp.ithome.com.tw/upload/images/20200321/20124767HK0Tgapdyp.png

FilterableProductTable :
將state初始化後利用props傳遞給子層。

class FilterableProductTable extends React.Component 
  {
    //初始化state
    constructor() 
    {
      super();
      this.state = {
        filterText: '',
        inStockOnly: false
      };
      //裡用bind複製function並綁定this
      this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
      this.handleInStockChange = this.handleInStockChange.bind(this);
    }
  
    //使用setState改變state中的值
    handleFilterTextChange(filterText) 
    {
      this.setState({
        filterText: filterText
      });
    }
    handleInStockChange(inStockOnly) 
    {
      this.setState({
        inStockOnly: inStockOnly
      })
    }
  
    render() {
      return (
        <div>
          <SearchBar
            //利用props傳遞state給子層
            filterText={this.state.filterText}
            inStockOnly={this.state.inStockOnly}
            onFilterTextChange={this.handleFilterTextChange}
            onInStockChange={this.handleInStockChange}
          />
          <ProductTable
            products={this.props.products}
            filterText={this.state.filterText}
            inStockOnly={this.state.inStockOnly}
          />
        </div>
      );
    }
  }

SearchBar :
使用onChange(元件內的值發生改變)來接收event,event發生後會呼叫並將改變的值傳入setState來更新state

class SearchBar extends React.Component 
  {
    constructor()
    {
      super();
      //裡用bind複製function並綁定this
      this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
      this.handleInStockChange = this.handleInStockChange.bind(this);
    }

    //當onChange(元件中的值發生改變)事件被觸發時,進入此function將改變的值傳入setState Function
    handleFilterTextChange(e) 
    {
      this.props.onFilterTextChange(e.target.value);
    }
    handleInStockChange(e) 
    {
      console.log(e.target.checked);
      this.props.onInStockChange(e.target.checked);
    }

    render() 
    {
      return (
        <form>
          <input
          type="text"
            placeholder="Search..."
            value={this.props.filterText}
            onChange={this.handleFilterTextChange}
          />
          <p>
          <input
            type="checkbox"
            checked={this.props.inStockOnly}
            onChange={this.handleInStockChange}
          />
            {' '}
            Only show products in stock
          </p>
        </form>
      );
    }
  }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言