reactjs - 实例化 React 组件时如何传入属性
问题描述
这是我的组件的样子:
class PersonProfileBadge extends React.Component {
constructor(props) {
super(props);
this.alias = this.props.alias;
//this.alias = 'hardcodedvalue';
}
render() {
return e(
'img',
{
src: `https://internal-cdn.com/somepath/?uid=${this.alias}`,
className: 'profile_photo'
}
);
}
}
现在我想实例化它并像这样渲染它
const navProfilePicture = document.querySelector('#profile_image');
ReactDOM.render((new PersonProfileBadge({'alias': 'stupidfatcat'})), navProfilePicture)
但是这样做会吐出这个错误
Objects are not valid as a React child (found: object with keys {props, context, refs, updater, alias}). If you meant to render a collection of children, use an array instead.
我对反应很陌生,我不知道如何正确地做到这一点。
这样做可行,但我无法传递别名的属性
ReactDOM.render(e(PersonProfileBadge), navProfilePicture);
解决方案
正确的做法是让您的环境改为支持 JSX:
const navProfilePicture = document.querySelector('#profile_image');
ReactDOM.render(
<PersonProfileBadge alias='stupidfatcat' />,
navProfilePicture
);
但是,如果您不能这样做,请React.createElement
在调用时使用ReactDOM.render
- 而不仅仅是在组件的渲染方法中:
ReactDOM.render(
e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
navProfilePicture
);
推荐阅读
- r - r : 从原始数据中获取值
- docker - ECONNREFUSED api 调用从 nextjs 使用 nginx dockerdocker 到 Strapi
- botframework - 未从 TeamsActivityHandler.onInvokeActivity 调用 onTurnError
- python - 将“axvspan”扩展到绘图的边界
- git - 'github.com/....' jenkins 的身份验证失败
- javascript - 如何从 iframe 获取当前页面 url 并显示在浏览器上
- r - 如何在除一个向量之外的所有元素上循环函数并将结果存储在数据框的单独列中
- curl - 使用 -d 命令时卷曲意外令牌
- amazon-web-services - AWS EKS:用户无权执行:iam:CreateRole on resource
- css - 在实时 sass 编译器中编译时出现 Sass 无效 css 错误