React 学习笔记_8 (Thinking in React - 4 )

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

目前已经建立了由上往下传递的props与state,但需要加入反向的资料流。为了确保当使用者改变表格内容后就会更新state已反映使用者输入的内容,在input上使用onChange(元件内的值发生改变)来接收event,event发生后会呼叫setState来更新state,并将更新后的state再次传递给子层并渲染到html中

流程图 :
http://img2.58codes.com/2024/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>      );    }  }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章