假设我使用的是正确的模式,那么我希望能够从inside 调用someFunc()(在<Home/>内部)<Wrapper/>。见下文:
var Home = React.createClass({
someFunc() {
console.log('How can I call this from <Wrapper/>?')
},
render() {
return <h1>Hello World</h1>
}
})
var Wrapper = (Home) => {
return React.createClass({
render() {
return <Home {...this.props}/>
}
})
}
var HomeWrapped = Wrapper(Home)
ReactDOM.render(<HomeWrapped/>, document.getElementById('root'))
Run Code Online (Sandbox Code Playgroud)
已更新解决方案:https : //codepen.io/oldgithub/pen/qPOZEj
我试图理解React的高阶组件的结构,但是所有资源仅假设您在编写时已经了解了扩展运算符在高阶组件中的用途:BaseComponent {... this.props} {。 ..this.state}。如果某个组件已经作为道具传入,为什么必须像这样散布道具?
import React, { Component } from 'react';
const EnhanceComponent = BaseComponent => {
return class EnhancedComponent extends Component {
state = {
name: 'You have been enhanced'
}
render() {
return (
<BaseComponent {...this.props} {...this.state} />
)
}
}
};
export default EnhanceComponent;
Run Code Online (Sandbox Code Playgroud) 我正在尝试为关闭元素构建一个通用 HOC,点击其空间外(通用关闭外部解决方案)。
在我看来,这可以通过 forwardRef 和 HOC 实现来实现,尽管官方文档中有一个示例,但我似乎无法正确理解。
所以我希望我的 HOC 创建对组件容器的引用。它正在包装,因为它具有跟踪点击并对其采取行动的处理程序。例如,假设我们有一个通用的 Dropdown 组件,人们希望我可以在该组件区域外的任何单击时关闭它。
我目前拥有的代码:
import React from 'react';
function withClose(Component) {
class ClickContainer extends React.Component {
constructor() {
super();
this.handleClose = this.handleClose.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClose);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClose);
}
handleClose(e) {
// I expect having here context of container of wrapped component to do something like
const { forwardedRef } = this.props; // <- I expect having context in forwardedRef variable
}
render() {
const { forwardedRef, …Run Code Online (Sandbox Code Playgroud) 所以我在 Next.js 应用程序中创建身份验证逻辑。我创建了/api/auth/login处理请求的页面,如果用户的数据良好,我将httpOnly使用 JWT 令牌创建一个cookie 并将一些数据返回到前端。这部分工作正常,但我需要某种方法来保护某些页面,以便只有登录的用户才能访问它们,而我在为此创建 HOC 时遇到了问题。
我看到的最好的方法是使用,getInitialProps但在 Next.js 网站上它说我不应该再使用它,所以我想使用getServerSideProps但那也不起作用,或者我可能做错了什么。
这是我的 HOC 代码:(cookie 存储在“userToken”名称下)
import React from 'react';
const jwt = require('jsonwebtoken');
const RequireAuthentication = (WrappedComponent) => {
return WrappedComponent;
};
export async function getServerSideProps({req,res}) {
const token = req.cookies.userToken || null;
// no token so i take user to login page
if (!token) {
res.statusCode = 302;
res.setHeader('Location', '/admin/login')
return {props: {}}
} else {
// we have token so …Run Code Online (Sandbox Code Playgroud) cookies node.js server-side-rendering higher-order-components next.js
首先,一些背景.
我正在使用Redux来管理我的应用程序的身份验证状态,并将其Auth作为Redux容器(或智能组件).
我创建了一个包装器(一个更高阶的组件)来获取Auth并返回它:
export default function AuthWrapper(WrappedComponent) {
class Auth extends Component {
... <Auth stuff here> ...
}
return connect(mapStateToProps, mapDispatchToProps)(Auth);
}
Run Code Online (Sandbox Code Playgroud)
在我看来,为了使用包装器,我只需要使用我想要在我的身份验证后面的组件来调用它.例如,假设我正在验证UserPage使用包装器调用的组件,àla:
const AuthenticatedUserPage = AuthWappper(UserPage)
但是,当我使用这样的包装时,React对我不满意.我收到以下错误:
Warning: AuthenticatedApp(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
Run Code Online (Sandbox Code Playgroud)
我最好的猜测是它不喜欢connectRedux在我从AuthWrapper... 返回时创建的-ified组件...这引出了我的问题:
当这些组件创建Redux容器时,React是否支持更高阶的组件?如果是这样,为什么React会抛出这个错误?
我试图理解为什么我的笑话/酶测试失败了。我有一个组件,我使用composeredux 中的函数,结构如下:
class MyComponent extends Component {
//code here
}
export default compose(
connect(mapStateToProps),
)(MyComponent)
Run Code Online (Sandbox Code Playgroud)
在我的笑话测试中,我这样做:
Import { MyComponent } from ‘app/MyComponent’;
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<MyComponent {…props} />);
}
it(‘Loads correctly’, () => {
expect(component.state(‘isLoading’)).toEqual(true);
expect(component.find(‘InnerComponent’).length).toBe(1);
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到诸如“无法读取未定义的属性‘状态’”之类的错误。我知道使用浅层渲染并不能提供我需要的确切结构,但我不确定还有什么方法可以尝试获得正确的结构。我尝试浅渲染包装的组件,然后在其中找到未包装的组件,就像这样,component = shallow(<MyComponent {...props} />).find('MyComponent').shallow();没有运气。任何其他建议将不胜感激。`
我正在尝试更习惯使用高阶组件,因此我正在重构应用程序。我有四个不同的组件,它们都重用相同的fetchData请求,以及错误/加载条件。我的计划是将这些可重复使用的数据放入 HOC。我已经尝试了 StackOverflow、Reddit、Github 等许多不同的示例,但没有一个在我的特定情况下有效。
这是我的 HOC:
const WithDataRendering = WrappedComponent => props => {
class WithDataRenderingComponent extends Component {
componentDidMount() {
this.props.fetchData(url)
}
render() {
if (this.props.hasErrored) {
return (
<p>
Sorry! There was an error loading the items:{" "}
{this.props.hasErrored.message}
</p>
)
}
if (this.props.isLoading) {
return (
<div>
<Skeleton count={10} />
</div>
)
}
return <WrappedComponent {...this.props} />
}
}
const mapStateToProps = state => {
return {
data: state.data,
hasErrored: state.dataHasErrored,
isLoading: state.dataIsLoading
}
} …Run Code Online (Sandbox Code Playgroud) javascript reactjs redux react-redux higher-order-components
一些简单的事情在这里绊倒了我的逻辑:
我有一个 HOC AnimateOnLoad,它react-router在页面组件中呈现默认内容(在内使用)。
const DefaultLayout = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={matchProps => (
<div className="page-container">
{AnimateOnLoad(
<div className="container">
<Head />
<Nav />
<Component {...matchProps} />
</div>
)}
<Footer />
</div>
)}
/>
);
Run Code Online (Sandbox Code Playgroud)
该animateONLoadHOC看起来是这样的:
const AnimateOnLoad = WrappedComponent =>
class Animator extends Component {
constructor(props) {
super(props);
this.ele = React.createRef();
}
componentDidMount() {
Kute.fromTo(
this.ele.current,
{ opacity: 0.3 },
{ opacity: 1, duration: 120 }
).start();
}
render() { …Run Code Online (Sandbox Code Playgroud) javascript higher-order-functions reactjs higher-order-components react-router-v4
假设我有一个高阶组件,类似于下面的琐碎定义,是从JavaScript模块导出的./hoc.js:
export const withStrong =
Component => props =>
<strong> <Component ...props/> </strong>
Run Code Online (Sandbox Code Playgroud)
假设我有一个名为的组件HelloMessage,那么这段JavaScript是等效的:
import { withStrong } from './hoc.js';
const HelloMessage = ...
const StrongMessage = withStrong(HelloMessage);
ReactDOM.render(
<StrongMessage name="Joe" />,
document.getElementById('react-app')
);
Run Code Online (Sandbox Code Playgroud) interop reason higher-order-components bucklescript reason-react
就此而言,我对 TypeScript 甚至 JavaScript 还很陌生。我一直在尝试围绕 Microsoft 的一个示例,介绍如何将 AzureAD 身份验证集成到 React 应用程序中。该示例使用 HOC 为组件提供身份验证。HOC 的声明如下所示:
function withAuthProvider<T extends React.Component<AuthComponentProps>>(
WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}
Run Code Online (Sandbox Code Playgroud)
其中大部分或多或少是清楚的。令我困惑的是WrappedComponent. 具体来说,我不明白new关键字在该上下文中的作用。
谁能帮我吗?
javascript ×8
reactjs ×8
redux ×2
bucklescript ×1
cookies ×1
enzyme ×1
interop ×1
jestjs ×1
next.js ×1
node.js ×1
react-redux ×1
reason ×1
reason-react ×1
typescript ×1