我有一个简单的react / redux应用程序,其中包含两个目标自动选择组件的搜索表单容器:
class QuoteBox extends Component {
onSelectSuggest(target, destination) {
this.props.setDestination(destination, target);
}
render() {
return (
<Destination
direction="From"
key="dest-from"
enterText={this.props.enterText.bind(this)}
onSelectSuggest={this.onSelectSuggest.bind(this, "origin")}
dataSource={this.props.originSuggests} />
<Destination
direction="To"
key="dest-to"
enterText={this.props.enterText.bind(this)}
onSelectSuggest={this.onSelectSuggest.bind(this, "destination")}
dataSource={this.props.destinationSuggests} />
)
}
}
function mapStateToProps(state) {
return {
originSuggests: state.originSuggests,
destinationSuggests: state.destinationSuggests,
origin: state.origin,
destination: state.destination
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
enterText: enterText,
setDestination: setDestination
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps )(QuoteBox)
而Destination是一个简单的组件,例如
export default class Destination extends Component {
render() {
return (
<AutoComplete
onUpdateInput = { _.debounce((term) => {
this.props.enterText(term);
this.setState({
searchText: term
})
}, 300) }
onNewRequest = {(x) =>{this.props.onSelectSuggest(x)}}
dataSource={this.props.dataSource} />
)
}
}
它们只是在某些事件上调用通过props传递的函数。
有自动绑定功能,但是在ES6类中不可用:https ://medium.com/@goatslacker/react-0-13-x-and-autobinding-b4906189425d#.nkv1cn32v我看到了许多替代方法,例如http:// www .ian-thomas.net / autobinding-react-and-es6-classes /或第三方库。
在将方法从容器传递到简单组件时,如何避免此bind(this)的现代方法是什么?
有很多现代方法,但是它们都围绕着相同的想法:)
您可以使用箭头功能:
<Destination
onSelectSuggest={destination => (
this.props.setDestination(destination, 'origin')
)}
/>
(我喜欢这一点,因为我们放弃了参数翻转onSelectSuggest
方法!)
对于更简单的绑定,可以使用ESNext绑定运算符(::
):
<Destination
enterText={::this.enterText}
/>
(显然,那个需要Babel)
编辑:2017年9月27日:“ bind”运算符似乎没有纳入规范。更现代的方法是使用属性初始值设定项语法(也是即将推出的JS功能,但我相信将其纳入语言的可能性更大):
class SomeComponent extends Component {
enterText = () => {
// body here
}
render() {
return <Destination enterText={this.enterText} />
}
}
最后,最有效的方法是在构造函数中进行绑定。
class QuoteBox extends Component {
constructor(props) {
super(props);
this.enterText = this.props.enterText.bind(this);
}
render() {
return (
<Destination
enterText={this.enterText}
/>
)
}
}
之所以更有效,是因为绑定非常慢,在您的示例中,绑定是在每个渲染上完成的。最好在初始化后再执行一次。
就是说,这两种方式都可能无关紧要。在性能成为问题之前,不要过分担心。React速度很快,除非您要处理非常复杂的组件树,否则差异可能微不足道。
同样,在AutoComplete中,应在构造函数中绑定去抖动的函数:
class Destination extends Component {
constructor(props) {
super(props);
this.updateInput = _.debounce(this.updateInput, 300)
updateInput(term) {
this.props.enterText(term);
this.setState({
searchText: term
})
}
render() {
return (
<AutoComplete
onUpdateInput={this.updateInput}
onNewRequest={this.props.onSelectSuggest}
/>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句