簡體   English   中英

未捕獲的錯誤:對象作為 React 子對象無效(找到:[object HTMLImageElement])

[英]Uncaught Error: Objects are not valid as a React child (found: [object HTMLImageElement])

在 reactjs 中,當道具更改時如何動態更新二維碼組件。 我正在使用這個 npm 包: https ://www.npmjs.com/package/kjua

componentWillMount()函數在第一次加載時工作,但它沒有更新,但如果我渲染{this.state.el}那么我會得到: *react-dom.development.js:57 Uncaught Error: Objects are not valid as a React child (found: [object HTMLImageElement]) 如果您打算渲染一組子項,請改用數組。*

 ``` import React, { Component } from 'react'; import kjua from "kjua"; class QrCodeOnAmountEntered extends Component { constructor(props) { super(props); this.state = { el: kjua({ text: `amount=${ this.props.text }&memo=xxxx` }), amount: this.props.text }; } componentWillMount(){ document.querySelector('body').appendChild(this.state.el); } render() { return ( <React.Fragment> QrCodeOnAmountEntered amount: {this.props.text} <p>Print QRCode here:</p>{this.state.el} </React.Fragment> ); } } export default QrCodeOnAmountEntered; ```

我需要能夠在道具數量值更改時動態更新 QRCode。

保存道具狀態是反應的反圖案(在的情況下props.text => this.state.amount ),和使用componentWillMount不推薦,而是使用componentDidMount組件安裝后問題的副作用。

我嘗試查看kjua的文檔,但它似乎已經過時了。 我假設您向它傳遞了一些“文本”,它會返回該文本的二維碼圖像。 HTMLImageElement似乎無法作為對象呈現,但也許,src將允許您將其呈現為<img>標簽。

render() {
  const { el } = this.state;
  return (
    <React.Fragment>
      QrCodeOnAmountEntered amount: {this.props.text}
      <p>Print QRCode here:</p>
      {el && <img src={el.src}/>}
    </React.Fragment>
  );
}

假設使用文本數據調用kjua返回一個新圖像,那么您想使用componentDidUpdate來檢查新道具是否已到達,如果是,則獲取新的 QR 圖像並保存到狀態:

componentDidUpdate(prevState, prevProps) {
  // if current text value is not equal to the previous, calculate
  // and save new QR code image in el, else ignore
  if (prevProps.text !== this.props.text) {
    const newQRcode = kjua({ text: `amount=${this.props.text}&memo=xxxx` });
    this.setState({ el: newQRcode });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM