javascript - 在不使用路由器的情况下渲染新组件
问题描述
我已经为 React 创建了一个应用程序,当它启动时,会呈现 App 组件。我希望当用户单击按钮或链接时,单击该链接时该按钮或链接必须位于 App 组件中,另一个组件将被呈现但不在 App 组件内,但只会呈现新组件在同一个网址中。至于这个新组件,它必须有一个类似的按钮,这样当用户点击时,只渲染 App 组件,而不渲染用户点击的这个组件,只渲染 App 组件。
我不知道我是否正确地解释了自己。如果您需要澄清,可以问我任何问题。
我的应用程序组件如下:
import React, { Component } from 'react';
import Touch from './Touch';
import '../App.css';
class App extends Component{
render() {
return(
<div>
<div className="wrapper" >
<button >NewComponent</button><NewComponent />???
<h1>Google Cloud Speech with Socket.io</h1>
<p id="ResultText"><span className="greyText">No Speech to Text yet</span></p>
</div>
<div className="buttonWrapper" >
<button className="btn" id="startRecButton" type="button"> Start recording</button>
<button className="btn" id="stopRecButton" type="button"> Stop recording</button>
</div>
</div>
);
}
}
export default App
我的 index.js 如下:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import App from './components/App.js';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
解决方案
如果您真的不想使用react-router
,则需要在组件的状态中存储一个值并更改渲染方法以反映按下了哪个按钮。如果您希望这些组件中的每一个都包含您需要切换的按钮,请执行以下操作:
class App extends Component {
constructor(props){
super(props);
this.state = {renderA: false,};
}
handleClick = (event) => {
this.setState((prevState) => ({renderA: !prevState.renderA}));
};
render = () => {
return(
<div>
{this.state.renderA ?
<ComponentA handleClick={this.handleCLick}/>:
<ComponentB handleClick={this.handleCLick}/>
}
</div>
);
};
} export default App;
// ComponentA
class ComponentA extends Component {
render = () => {
return(
<div>
// what you want inside your first page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentA;
// ComponentB
class ComponentB extends Component {
render = () => {
return(
<div>
// what you want inside your second page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentB;
但是使用react-router
可能也适合您的情况,如果您要编写一个大型应用程序,您应该使用它而不是根据用户输入在同一个子组件中呈现不同的子组件。
推荐阅读
- javascript - onChange(e) 中的“e”是什么?
- unix - 使用 AWK 读取文件的 1 行后跳过 2 行
- linux - 打印没有该列第一项的列
- ruby-on-rails - Rails 5.0:添加引用现有表的自连接表
- android - 我怎么解决这个问题。(错误:找不到字段的吸气剂。)
- google-bigquery - 如何在 Google Big Query 中展平一行中的值
- python-3.x - 在python中迭代时间戳
- vb.net - WebBrowser 中的 InnerHtml
- groovy - Geb 等待元素消失
- oracle - 如何解决 Evosuite 生成的测试中的 oracle jdbc 代理类错误?