简体   繁体   中英

How do I include my custom Component using `require` instead of `include`

I have built a simple React Component using nwb as described in this guide .

It's a very simple Component that is just a button:

import t from 'prop-types'
import React, {Component} from 'react'

class LoadingButton extends Component {
  static propTypes = {
    disabled: t.bool,
    loading: t.bool,
    type: t.string,
  }
  static defaultProps = {
    disabled: false,
    loading: false,
    type: 'button',
  }
  render() {
    let {children, disabled, loading, type, ...props} = this.props
    if (loading) {
      disabled = true
    }
    return <button disabled={disabled} type={type} {...props}>
      {children}
    </button>
  }
}

export default LoadingButton

In another project, after using npm link , I am able to import this Component doing something like this:

import LoadingButton from 'react-loading-button'

And it works!

在此处输入图像描述

But my question is, I also need to include this Component using require (inside an older codebase). I would like to do something like this:

var LoadingButton = require("react-loading-button");

Unfortunately, this approach doesn't work for me. It gives me this error:

Error: Objects are not valid as a React child (found: [object Module]). If you meant to render a collection of children, use an array instead.

在此处输入图像描述

I have built the component using nwb, which states:

By default, nwb will create a CommonJS build for your project in lib/, which is the primary way it will be used when installed via npm, with default package.json main config pointing to lib/index.js.

So I am a bit confused about why the require doesn't work.

Has anyone had any experience with this approach?

I tried with function/class style components, var LoadingButton = require("react-loading-button").default; seems working fine, codebase is not exactly the same, but worth trying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM