【问题标题】:How to properly add and use third party/npm libraries in Reactjs?如何在 Reactjs 中正确添加和使用第三方/npm 库?
【发布时间】:2019-07-22 17:16:14
【问题描述】:

我正在学习 react,这是我第一次在 react 中使用库。我正在尝试使用watermark-js。我已经阅读了有关如何使用 npm install <library name> save 在我的 react package.json 中添加 npm 包的文章。这是 package.json 中显示 watermarkjs 的部分

"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "2.1.8",
    "save": "^2.4.0",
    "watermarkjs": "^2.0.0"

现在在我的 App.js 组件中,我已将其作为模块导入,并在 react 文档中使用由 watermarkjs 在 componentDidMount 方法中提供的 sn-p。下面是我完整的 App.js 组件。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Components/Form';
import ImageWaterMark from './Components/ImageWaterMark';
import image1 from './test-image.jpg'
import image2 from './download.jpg'
import { watermark } from 'watermarkjs'
class App extends Component {

  componentDidMount() {

    //Snippit 

    watermark([{ image1 }, { image2 }])
      .image(watermark.image.lowerRight(0.5))
      .then(function (img) {
        document.getElementById('lower-right').appendChild(img);
      });
  }
  render() {


    return (
      <div className="App">
        <div ref="water"></div>
      </div>
    );
  }
}

export default App;

有 2 个问题我似乎无法理解。第一个

如何将此 sn-p 作为 ref 传递给渲染方法,如 文档?

二次App通过以下错误

TypeError: 无法读取未定义的属性“水印”

我已经阅读了很多文章并观看了视频,但我还没有理解使用库的概念。任何帮助将非常感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    watermarkjs 使用默认导出,而不是命名导出。改变这个:

    import { watermark } from 'watermarkjs'`
    

    到这里:

    import watermark from 'watermarkjs'
    

    至于如何使用它,一旦加载,您应该调用 setState 并返回结果。这将再次渲染您的组件,您可以使用该值,但您认为合适。例如:

      componentDidMount() {
        watermark([{ image1 }, { image2 }])
          .image(watermark.image.lowerRight(0.5))
          .then((img) => {
            this.setState({ img });
          });
      }
    
      render() {
        return (
          <div className="App">
            <div ref="water">
              {this.state.img && /* whatever you want to do with the image */ }
            </div>
          </div>
        );
      }
    

    我不确定 img 解析到什么,所以不知道你在渲染函数中到底放了什么。如果是url字符串,则为{this.state.img &amp;&amp; &lt;image src={this.state.img} /&gt;}

    【讨论】:

    • 谢谢你的回答,我正在尝试使用它。如果可行,我会发表评论
    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多