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

标签 javascript reactjs

在 reactjs 中,我如何在 props 更改时动态更新 QR 码组件。我正在使用这个 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; ```

我需要能够在 Prop 数量值发生变化时动态更新 QRCode。

最佳答案

将 Prop 保存到状态是一种 react 反模式(在 props.text => this.state.amount 的情况下),并且使用 componentWillMount不推荐,而是使用 componentDidMount在组件安装后发出副作用。

我试着查看 kjua 的文档但它看起来很过时。我假设您将一些“文本”传递给它,它会返回该文本的 QR 码图像。 HTMLImageElement在作为对象的 react 中似乎不可渲染,但也许 ,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检查新 Prop 是否已到达,如果是,则获取新的 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 });
  }
}

关于javascript - Uncaught Error : Objects are not valid as a React child (found: [object HTMLImageElement]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176003/

相关文章:

javascript - React 到底什么时候渲染——在各种异步调用、socketIO 和 React 之间管理状态的问题

node.js - 使用 React 进行 Webpack 配置

reactjs - 如何不在登陆(登录页面)页面上呈现标题,但总是在 react-router v6 中的所有其他页面上呈现标题?

javascript - 关于此向导表单布局的一般方式的建议

javascript - wp 页面中出现奇怪的 javascript 代码

javascript - 在 WordPress 主题模板中排队 jQuery 插件

node.js - React Native Ios 错误 - ENOENT : no such file or directory, uv_cwd (null))

javascript - 如何通信多个组件

javascript - 如何在 Spotify 中从特定时间开始播放歌曲

javascript - 将参数从屏幕传递到 Header 组件 react 导航