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