[英]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.