在 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/