Mih*_*hai 5 javascript reactjs react-router redux react-router-v4
我有以下课程
class MatchBox extends React.Component {
constructor(props) {
super(props);
this.countdownHandler = null;
this.showBlocker = true;
this.start = this.start.bind(this);
}
start() {
...
}
render() {
...
return (
<div style={ styles.mainContainer } className="fluid-container">
...
</div>
);
}
};
function mapStateToProps(state) {
...
}
function matchDispatchToProps(dispatch) {
...
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(MatchBox));
Run Code Online (Sandbox Code Playgroud)
这个课程中使用的
class GameBox extends React.Component {
constructor(props) {
super(props);
...
}
render() {
var mainElement = null;
switch(this.props.mainElement.element) {
case 'SEARCHING': mainElement = <SearchingBox gameType={ this.props.gameType }/>; break;
case 'MATCH': mainElement = <MatchBox ref='matchBox'/>; break;
default: mainElement = <SearchingBox/>;
}
return (
<div style={ styles.mainContainer } className="fluid-container">
{ mainElement }
</div>
);
}
};
function mapStateToProps(state) {
...
}
function matchDispatchToProps(dispatch) {
...
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(GameBox));
Run Code Online (Sandbox Code Playgroud)
我无法得到对象MatchBox的引用.我尝试过this.refs.matchBox并且为null,也尝试直接从ref(ref={(r) => { // r is null } })获取,我不知道该怎么办.我正在使用react-router-dom 4,我不知道函数是否withRouter会影响结果组件.
它不漂亮,但我认为这是解决方案.withRouter通过wrappedComponentRef回调公开子参考,这让我们得到了connect回应.getWrappedInstance如果你withRef像你一样传递属性,那就暴露了它的子引用.所以你必须将两者结合起来.
class GameBox extends React.Component {
matchboxRefCallback = (connectHOC) => {
this.matchboxRef = connectHOC ? connectHOC.getWrappedInstance() : null;
}
render() {
return <MatchBox wrappedComponentRef={this.matchboxRefCallback}/>;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1077 次 |
| 最近记录: |