首页 > 解决方案 > 实例化 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);

标签: reactjs

解决方案


正确的做法是让您的环境改为支持 JSX:

const navProfilePicture = document.querySelector('#profile_image');
ReactDOM.render(
  <PersonProfileBadge alias='stupidfatcat' />,
  navProfilePicture
);

但是,如果您不能这样做,请React.createElement在调用时使用ReactDOM.render- 而不仅仅是在组件的渲染方法中:

ReactDOM.render(
  e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
  navProfilePicture
);

推荐阅读