反应全局组件 [英] React global component

查看:44
本文介绍了反应全局组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自vue.js背景,最近我才开始研究React.

I am coming from a vue.js background and I have just recently started looking into react.

我有一个组件:PageContent.jsx,我希望使用它而不必不断地导入它,以便能够在渲染功能(JSX)中使用它.

I have a component: PageContent.jsx and I wish to use it without constantly having to import it to be able to use it inside the render function (JSX).

可以使用以下方法对组件进行全球化:

In vue it is possible to globalise a component using:

Vue.component(componentName, componentObject)

有什么类似的反应吗?

推荐答案

嗯,React中没有任何类型的全局"组件.每个组件都必须作为prop导入或传递.不过,如果您要避免向每个文件添加导入,则有几种选择:

Hmm, there isn't any kind of "global" component in React. Each component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:

1)创建一个高阶组件,以呈现PageContent 和包装的组件.

1) Create a Higher Order Component that renders the PageContent and the wrapped component.

import PageContent from './PageContent';

const withPageContent = WrappedComponent => {
  return class extends React.Component {
    render () {
      return (
        <PageContent>
          <WrappedComponent />
        </PageContent>
      )
    }
  }
};

export default withPageContent;

// Usage

import withPageContent from './withPageContent';

class MyComponent extends React.Component {
  render () {
    return (
      <div>
        I'm wrapped in PageContent!
      </div>
    )
  }
}

export default withPageContent(MyComponent);

2)将 PageContent 作为道具传递给组件:

2) Pass PageContent as a prop to a component:

import PageContent from './PageContent';

export default class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Child1 content={PageContent} />
        <Child2 content={PageContent} />
      </React.Fragment>
    )
  }
}

// Usage

export default class Child1 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}

export default class Child2 extends React.Component {
  render () {
    const PageContent = this.props.content;
    return (
      <PageContent>
        I'm wrapped in PageContent!
      </PageContent>
    )
  }
}

这篇关于反应全局组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆