在按钮单击事件上渲染 React 组件



我有一个极简主义的登陆页面,有两个文本和一个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的情况下做到这一点,因为我认为这太小而无法实现路由。谢谢。

在您的州使用布尔标志。单击并执行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>
);
}
}

最新更新