react组件

2018-10-01  本文已影响0人  灯光树影

一、什么是组件

组件(Component)是对数据和方法的简单封装,react还包括对html的简单的简单封装

二、react组件的分类

class TodoListUI extends Component{
    render(){
        return (
            <div style={{margin: '20px'}}>
                <div>
                    <Input placeholder='todo item' style={{width: '300px', marginRight: '10px'}} value={this.props.inputValue} onChange={this.props.changeInputValue}></Input>
                    <Button type="primary" onClick={this.props.addItem}>提交</Button>
                </div>
                <List
                    style={{width: '300px', marginTop: '20px'}}
                    bordered
                    dataSource={this.props.list}
                    renderItem={(item,index) => (<List.Item onClick={(index) => {this.props.handleItemDelete(index)}}>{item}</List.Item>)}
                />
            </div>
        );
    }
}
class TodoList extends Component {

  constructor(props){
    super(props)
    this.state = store.getState()
    this.changeInputValue = this.changeInputValue.bind(this)
    this.addItem = this.addItem.bind(this)
    this.handleStoreChange = this.handleStoreChange.bind(this)
    this.handleItemDelete = this.handleItemDelete.bind(this)
    store.subscribe(this.handleStoreChange)
  }

  render() {
    return (
      <TodoListUI 
        inputValue = {this.state.inputValue}
        list = {this.state.list}
        changeInputValue = {this.changeInputValue}
        addItem = {this.addItem}
        handleItemDelete = {this.handleItemDelete}
      />
    );
  }

  componentDidMount(){
    axios.get('/getData').then(function(res){
      console.log(res.data)
    })
  }

  changeInputValue(e){
    const action = getChangeInputValueAction(e.target.value)
    store.dispatch(action)
  }

  addItem(){
     const action = getAddTodoItemAction()
     store.dispatch(action)
  }

  handleStoreChange(){
    this.setState(store.getState())
  }

  handleItemDelete(index){
    const action = getDeleteTodoItemAction(index)
    store.dispatch(action)
  }
}
const TodoListUI = (props) => {
    return(
        <div style={{margin: '20px'}}>
            <div>
                <Input placeholder='todo item' style={{width: '300px', marginRight: '10px'}} value={props.inputValue} onChange={props.changeInputValue}></Input>
                <Button type="primary" onClick={props.addItem}>提交</Button>
            </div>
            <List
                style={{width: '300px', marginTop: '20px'}}
                bordered
                dataSource={props.list}
                renderItem={(item,index) => (<List.Item onClick={() => {props.handleItemDelete(index)}}>{item}</List.Item>)}
            />
        </div>
    ) 
}

无状态组件没有生命周期函数,所以性能可以提高

上一篇 下一篇

猜你喜欢

热点阅读