在React.js中的不同位置渲染不同的元素

时间:2017-11-02 15:01:23

标签: reactjs

在父文件(NotificationParent)中,我得到一些这样的数据:

=Sum(IIf(Fields!MessagingSLA.Value = "NA", 1, 0), "Alarms") / (CountRows("Alarms"))

在第二个文件(NotificationCount)中,我在屏幕上渲染它,如:

class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            notifications: []
        }
    }

    componentDidMount() {
        var self = this;

        axios.get('url here').then(function (response) {
            self.setState({
                notifications: response.data
            });
        })
    }

    render() {
        const notifications = this.state.notifications.map( (notification, i) => <NotificationCount key={i} {...notification} /> );

        return (
            <div>
                {notifications}
            </div>
        )
    }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('notifications')
);

ReactDOM.render(
    <NotificationTotal />,
    document.getElementById('notificationcount')
);

在第三个文件(NotificationTotal)中,我想显示它拥有的标题数量(例如:2):

render() {
    return (
        <li>
            <a href="#">
                {this.props.title}
            </a>
        </li>
    )
}

在第三个文件(NotificationTotal)中,我无法获得金额,因为它不知道道具。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Chase deAnda通过创建额外功能提供了最终解决方案。父文件的代码:

let outsideData = [];

class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            notifications: []
        }
    }

    componentDidMount() {
        ...
    }

    componentWillUnMount() {
        ...
    }

    componentDidUpdate(nextProps, nextState) {
        outsideData = nextState.notifications;
    }

    render() {
        const notifications = this.state.notifications.map( (notification, i) => <NotificationCount key={i} {...notification} /> );

        renderNotifications(this.state.notifications);

        return (
            <div>
                {notifications}
            </div>
        )
    }
}

const Notification = ({ title, read }) => (
    <div>
        <span>{title}</span>
        <span>{read}</span>
    </div>
);

ReactDOM.render(
    <Parent />,
    document.getElementById('notifications')
);

function renderNotifications (notifications) {
    ReactDOM.render(
        <NotificationTotal notifications={notifications} />,
        document.getElementById('notificationcount')
    );
}