首页 > 解决方案 > React Props 不在 UI 上显示数据

问题描述

我正在学习反应

在处理 Props 时,我创建了一个组件并在我的 index.jsx 中使用该组件。但是通过 props 传递的值不会显示在 UI 上。

使用props.jsx

import React from 'react';
class UsingProps extends React.Component {
    render() {
        return (
            <div>
                <p>{this.props.headerProp}</p>
                <p>{this.props.contentProp}</p>
            </div>
        );
    }
}

export default UsingProps;

索引.jsx

import React from 'react';
import UsingProps from './Props/UsingProps.jsx';

class App extends React.Component {
    render() {
        return (
            <div>
                <UsingProps />
            </div>
        );
    }
}

const myElement = <App headerProp="Header from props!!!" contentProp="Content from props!!!" />;
ReactDOM.render(myElement, document.getElementById('root'));

export default App;

标签: reactjs

解决方案


您将 放在headerProp组件上App,而不是UsingProps组件上,这是您尝试访问它的地方。您需要将其修改为:

class App extends React.Component {
    render() {
        return (
            <div>
                <UsingProps headerProp="Header from props!!!" contentProp="Content from props!!!" />
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

推荐阅读