初探React编程逻辑(结合业务需求)
看完React官网的核心知识点,思考如何应用在实际的项目中呢?
第一步:先将UI设计图划分成各个React组件,划分的规则可以根据最小功能单位,或者是根据JSON数据模型。
第二部:通过React写静态页面结构。
第三步:添加动态交互功能。
总结:子组件的数据源来自父组件,边界情况下会出现undefined,所以在渲染子组件的之前需要判断从父组件传来的数据是否是有效数据,如果不是直接return null;
本代码思路就是顶层的父组件处理所有的业务逻辑。
class Item extends React.Component { render() { return ( <tr> <td>{this.props.name}</td> <td>{this.props.price}</td> </tr> ) } } function Category(props){ const categoryItems = props.category if(!categoryItems.length) { return null } return ( <div> <td><b>{categoryItems[0].category}</b></td> <div> {categoryItems.map((item)=> { return ( <Item name={item.name} price={item.price}/> ) })} </div> </div> ) } class Table extends React.Component { render() { let sporting_goods = [], electronics = [] const products = this.props.products for(let i=0; i<products.length; i++){ if(products[i].category === 'Sporting Goods') { sporting_goods.push(products[i]) } else { electronics.push(products[i]) } } return( <div> <table> <tr> <th>Name</th> <th>Price</th> </tr> </table> <Category category={sporting_goods}/> <Category category={electronics}/> </div> ) } } class Search extends React.Component { render() { return ( <form> <input type="text" name="value" value={this.props.value} onChange={this.props.onChange} placeholder="search"/><br/> <label> <input type="checkbox" name="isStock" checked={this.props.isStock} onChange={this.props.onChange}/> Only show products in stock </label> </form> ) } } class ProductFilter extends React.Component { constructor(props) { super(props) this.state = { value: '', isStock: false } this.handleChange = this.handleChange.bind(this) } handleChange(e) { const value = (e.target.type === 'checkbox') ? e.target.checked : e.target.value const name = e.target.name this.setState({ [name]: value }) } render() { let ret = [] if(this.state.value) { if(this.state.isStock){ PRODUCTS.forEach((item) => { if(!item.stocked) { return } if(item.name.toUpperCase().indexOf(this.state.value.toUpperCase()) >= 0) { ret.push(item) } })} else { PRODUCTS.forEach((item) => { if(item.name.toUpperCase().indexOf(this.state.value.toUpperCase()) >= 0) { ret.push(item) }}) } } else { ret = PRODUCTS } return ( <div> <Search value={this.state.value} isStock={this.state.isStock} onChange={this.handleChange}/> <Table products={ret}/> </div> ) } } ReactDOM.render(<ProductFilter />, document.getElementById('root')) const PRODUCTS = [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'} ]