为事件设置组件或元素回调时,教程和文档显示如下代码:
'use strict';
import React from 'react';
let FooComponent = React.createClass({
handleClick(args) {
...
},
render() {
return <div>
<h1>Some title</h1>
<button onClick={this.handleClick}>Click Me!</button>
</div>
}
};
export default FooComponent;
Run Code Online (Sandbox Code Playgroud)
但是这个handleClick方法可以从这个组件中访问,如果我在另一个组件上使用FooComponent并为它分配一个引用我可以从另一个组件访问handleClick.
'use strict';
import React from 'react';
import FooComponent from './FooComponent';
let BarComponent = React.createClass(
handleBarComponentClick(e) {
this.refs.fooComponent.handleClick(null);
},
render() {
return <div>
<FooComponent ref="fooComponent" />
<button onClick={this.handleBarComponentClick}>Other click</button>
</div>
}
);
export default BarComponent;
Run Code Online (Sandbox Code Playgroud)
我不喜欢我可以访问该方法的事实,在我看来应该是私有的,或者我不必担心它.但为了解决这个问题,我开始在我的项目中使用这种"好/坏做法"来避免访问该方法.
'use strict';
import React from 'react';
function handleClick(args) {
...
}
let …Run Code Online (Sandbox Code Playgroud) 我无法弄清楚,当我想从其他组件调用我的容器中的动作时,如何做出正确的解决方案,顺便说一下我想使用扩展运算符,因为我需要在我的组件中传递太多参数而不想描述他们都是.
我知道我可以通过道具传递来自redux商店的所有道具,比如菜单中的这个例子,但是我的组件太嵌套了,我必须在巢中的eighter组件中发送道具
render() {
return (
<div className="wrapper">
<Menu {...this.props} />
</div>
);
}
}
const mapStateToProps = reduxStore => (
{
app: reduxStore.app
}),
mapDispatchToProps = dispatch => ({appActions: bindActionCreators(appActions, dispatch)});
export default connect(mapStateToProps, mapDispatchToProps)(App);Run Code Online (Sandbox Code Playgroud)
所以,我决定将我的嵌套组件与redux store连接起来,因为我需要在我的嵌套组件中使用主容器组件中的store和actions.但是这个解决方案不起作用,因为我使用扩展运算符到我的嵌套组件.
render() {
return <Link activeClassName='active' onClick={this.props.appActions.closeMenu} {...this.props} />;
}Run Code Online (Sandbox Code Playgroud)
使用spread运算符非常重要,因为组件从其父组件获取的参数太多,如果我不使用{... this.props},我必须这样写:
render() {
const { to, onlyActiveOnIndex, className, specialIcons } = this.props;
return <Link activeClassName='active' onClick={this.props.appActions.closeMenu} to={to} specialIcons={specialIcons} onlyActiveOnIndex={onlyActiveOnIndex} className={className} >{this.props.children}</Link>;
}Run Code Online (Sandbox Code Playgroud)
而且,我必须连接到常见的redux存储,当我连接时,发生一个错误,因为我的组件使用{... this.props}并且它获取所有道具,包括来自容器和组件的动作不知道他们怎么做 我找到了这个问题的一个解决方案,但我不确定它是正确的变种.我使用扩展运算符克隆道具,但删除包含来自公共存储的新函数(操作)的属性.
render() {
let oldProps = {...this.props};
delete …Run Code Online (Sandbox Code Playgroud)