流程圖 :
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>
);
}
}