我正在尝试与构建 React 应用程序的团队合作,并尝试找出创建“高阶”React 组件(一个包装另一个组件)的最佳方法,以与 Redux 数据存储结合执行身份验证。
到目前为止,我的方法是创建一个由一个函数组成的模块,该函数根据是否存在经过身份验证的用户返回一个新的 React 组件。
export default function auth(Component) {
class Authenticated extends React.Component {
// conditional logic
render(){
const isAuth = this.props.isAuthenticated;
return (
<div>
{isAuth ? <Component {...this.props} /> : null}
</div>
)
}
}
...
return connect(mapStateToProps)(Authenticated);
}
这使得我团队中的其他人可以轻松指定组件是否需要某些权限。
render() {
return auth(<MyComponent />);
}
如果您正在执行基于角色的检查,则此方法很有意义,因为您可能只有几个角色。在这种情况下,你可以直接打电话auth(<MyComponent />, admin)
.
对于基于权限的检查来说,传递参数变得很麻烦。然而,在构建组件时在组件级别指定权限可能是可行的(以及在团队环境中可管理的)。设置静态方法/属性似乎是一个不错的解决方案,但是,据我所知,es6 类导出为函数,这不会显示可调用方法。
有没有办法访问导出的 React 组件的属性/方法,以便可以从包含的组件中访问它们?
onEnter很棒,并且在某些情况下很有用。然而,以下是 onEnter 无法解决的一些常见身份验证和授权问题:
另一种方法是使用高阶组件。
您可以使用 Redux-auth-包装器 https://github.com/mjrussell/redux-auth-wrapper提供高阶组件,以便于阅读和应用组件的身份验证和授权约束。
要获取子方法,您可以使用:refs, callback and callback from refs
要获取子道具,您可以使用:this.refs.child.props.some or compInstance.props.some
方法和道具示例:
class Parent extends Component {
constructor(props){
super(props);
this.checkChildMethod=this.checkChildMethod.bind(this);
this.checkChildMethod2=this.checkChildMethod2.bind(this);
this.checkChildMethod3=this.checkChildMethod3.bind(this);
}
checkChildMethod(){
this.refs.child.someMethod();
console.log(this.refs.child.props.test);
}
checkChildMethod2(){
this._child2.someMethod();
console.log(this._child2.props.test);
}
checkChildMethod3(){
this._child3.someMethod();
console.log(this._child3.props.test);
}
render(){
return (
<div>
Parent
<Child ref="child" test={"prop of child"}/>
<ChildTwo ref={c=>this._child2=c} test={"prop of child2"}/>
<ChildThree returnComp={c=>this._child3=c} test={"prop of child3"}/>
<input type="button" value="Check method of child" onClick={this.checkChildMethod}/>
<input type="button" value="Check method of childTwo" onClick={this.checkChildMethod2}/>
<input type="button" value="Check method of childThree" onClick={this.checkChildMethod3}/>
</div>
);
}
}
class Child extends Component {
someMethod(){
console.log('someMethod Child');
}
render(){
return (<div>Child</div>);
}
}
class ChildTwo extends Component {
someMethod(){
console.log('someMethod from ChildTwo');
}
render(){
return (<div>Child</div>);
}
}
class ChildThree extends Component {
componentDidMount(){
this.props.returnComp(this);
}
someMethod(){
console.log('someMethod from ChildThree');
}
render(){
return (<div>Child</div>);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)