首页 > 解决方案 > 在不使用路由器的情况下渲染新组件

问题描述

我已经为 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();

标签: javascriptreactjs

解决方案


如果您真的不想使用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可能也适合您的情况,如果您要编写一个大型应用程序,您应该使用它而不是根据用户输入在同一个子组件中呈现不同的子组件。


推荐阅读