mixin
在React中使用mixin
import React from 'react';
import PureRenderMinxin from 'react-addons-pure-render-mixin';
React.createClass({
mixins: [PureRenderMinxin],
render(){
render <div>foo</div>;
}
});
ES6 Classes与decorator
使用我们推荐的ES6 classes形成构建组件时,它并不支持mixin.
高阶组件
属性代理
import React, {Component} from 'React';
const MyContainer = (WrapperComponent) =>
class extends Component {
render() {
render <WrapperComponent {...this.pros} />;
}
}
组合式组件开发实践
组件再分离
class SelectInput extends Component {
static displayName = 'SelectInput';
render() {
const {selectedItem, isActive, onClickHeader, placeholdler} = this.props;
const {text} = seletedItem;
return (
<div>
<div onclick={onClickHeader}>
<input type="text" disabled value={text} placeholder={placeholder} />
<Icon className={isActive} name="angle-down" />
</div>
</div>
);
}
}
组件再抽象
// 完成SearchInput与List的交互
const searchDecorator = WrapperComponent => {
class SearchDecorator extends Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
}
handleSearch(keyword) {
this.setState({
data: this.props.data,
keyword,
});
this.props.onSearch(keyword);
}
render(){
const {data, keyword} = this.state;
return (
<WrapperComponent
{...this.props}
data={data}
keyword={keyword}
onSearch={this.handleSearch}
/>
);
}
}
return searchDecorator;
}
//完成List数据请求
const asyncSelectDecorator = WrapperComponent => {
class AsyncSelectDecorator extends Component {
componentDidMount(){
const {url, params} = this.props;
fetch(url, {params}).then(data => {
this.setState({
data,
});
});
}
render(){
return (<WrapperComponent {...this.props} data={this.state.data} />);
}
}
return AsyncSelectDecorator;
}
// 组合
const FinalSelector = compose(asyncSelectDecrator, searchDecorator, selectedItemDecorator)(Selector);
class SearchSelect extends Component {
render(){
return (
<FinalSelector {...this.props}>
<SelectInput />
<SearchInput />
<List />
</FinalSelector.
);
}
}