一、什么是组件
组件(Component)是对数据和方法的简单封装,react还包括对html的简单的简单封装
二、react组件的分类
-
UI组件
顾名思义,UI组件就是仅仅负责页面表现的组件,没有或者只有少量方法的封装。
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)
}
}
-
无状态组件
当UI组件只有render函数时,可以用箭头方法直接导出UI组件,props通过参数接收,组件中没有props,所以是无状态的组件
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>
)
}
无状态组件没有生命周期函数,所以性能可以提高
网友评论