19React中手动切换组件

如图效果 点击两个不同的按钮 分别显示不同的组件内容

构建两个组件

分别为Child12.js和Child13.js

import React, { Component } from 'react'

export default class Child12 extends Component {
    render() {
        return (
            <div>
                我是子组件12
            </div>
        )
    }
}
import React, { Component } from 'react'

export default class Child13 extends Component {
    render() {
        return (
            <div>
                我是子组件13
            </div>
        )
    }
}

在app.js中分别引入以后

在对应的事件中 点击按钮对 targetChild重新进行赋值即可

   <button onClick={
                    ()=>{
                        this.setState({
                            targetChild:Child12
                        })
                    }
                }>点击显示12</button>
                <button onClick={
                     ()=>{
                        this.setState({
                            targetChild:Child13
                        })
                    }
                }>点击显示13</button>
                <this.state.targetChild>
                </this.state.targetChild>
发布了19 篇原创文章 · 获赞 31 · 访问量 5723

猜你喜欢

转载自blog.csdn.net/ldc121xy716/article/details/104009124