在按钮Click事件上渲染React组件

时间:2018-10-22 15:03:08

标签: javascript reactjs buttonclick

我有一个极简的登录页面,其中包含两个文本和一个div,其中包含两个按钮。单击这些按钮之一后,我要呈现App组件。

这是我到目前为止尝试过的:

import React from 'react';
import App from '../App';

export default class Landing extends React.Component {

constructor(){
    super();
}

launchMainWithoutProps = () => {
    return (<App />)
};

showAppMain =() => {
    console.log('Silk board clicked');
    this.launchMainWithoutProps();
};   

render() {
    return (
        <div className='landing'>
            <div className="centered">
                <div className="introText">
                    <h3>Welcome to KahanATM</h3>
                    <h5>A Simple Web App with React to find ATMs closest to you (3km radius) or from Silk Board Flyover</h5>
                </div>

                <div className="buttonsLayout">

                    <button
                        className='getLocation'
                        onClick={this.showAppMainWithLocation}>
                        Get My Location
                    </button>

                    <button
                        className='silkBoard'
                        onClick={this.showAppMain}>
                        Central Silk Board
                    </button>
                </div>
            </div>
        </div>
    );
}

}

但是,当单击按钮时,控制台中仅显示日志。不管有没有react-router,我该怎么办,因为我认为这太小了,无法实现路由。谢谢。

1 个答案:

答案 0 :(得分:2)

在您的状态下使用布尔标志。单击并执行showAppMain时,将状态变量设置为true,这将导致渲染函数返回<App />

import React from 'react';
import App from '../App';

export default class Landing extends React.Component {

    constructor() {
        super();

        this.state = {
            shouldShowMain: false,
        };

        this.showAppMain = this.showAppMain.bind(this);
    }

    showAppMain() {
        console.log('Silk board clicked');
        this.setState({shouldShowMain: true});
    };   

    render() {
        if (this.state.shouldShowMain) {
            return (<App />);
        }

        return (
            <div className='landing'>
                <div className="centered">
                    <div className="introText">
                        <h3>Welcome to KahanATM</h3>
                        <h5>A Simple Web App with React to find ATMs closest to you (3km radius) or from Silk Board Flyover</h5>
                    </div>

                    <div className="buttonsLayout">

                        <button
                            className='getLocation'
                            onClick={this.showAppMainWithLocation}>
                            Get My Location
                        </button>

                        <button
                            className='silkBoard'
                            onClick={this.showAppMain}>
                            Central Silk Board
                        </button>
                    </div>
                </div>
            </div>
        );
    }
}