gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:19:58 24 4
gpt4 key购买 nike

我有一个极简主义的着陆页,其中包含两个文本和一个 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 来执行此操作,因为我认为这太小而无法在其中实现路由。谢谢。

最佳答案

在您所在的州使用 bool 标志。当你点击并执行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>
);
}
}

关于javascript - 在按钮单击事件上渲染 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52932415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com