使用JSX渲染Bootstrap组件

问题描述 投票:0回答:2

我无法弄清楚如何在React应用程序中使用JSX创建Boostrap组件。最终目标是在单击第一个按钮时在“ newBtnSpace” div中获得新按钮。我尝试使用show.hide方法,但是我想使用此渲染器来显示某些如果单击的东西列表。代码:

./ components / newBSBtnSpaceFunc.js

    import React, { Component } from 'react'
    import { Button } from 'reactstrap'

    export default function NewBSBtnFunc() {
        return React.createElement(
            Button,
            {variant: 'primary'},
            'New Button',
            {id: "newBtn"}
            )   
           }

./ components / BSBtn.js

     import React, { Component } from 'react'
     import { Button } from 'reactstrap'
     import NewBSBtnFunc from "./NewBSBtnFunc"


     export default class BSBtn extends Component {

     render() {
       return (
          <div>
            <Button onClick={NewBSBtnFunc}>Click Me</Button>
            <div id="newBtnSpace"></div>
          </div>
       )
      }

}

App.js

     import React from 'react';
     import 'bootstrap/dist/css/bootstrap.min.css';
     import BSBtn from "./components/BSBtn"


     function App() {
      return (
       <div>
        <BSBtn></BSBtn>
      </div>
     );
    }

   export default App;
reactjs button components reactstrap
2个回答
0
投票

您可以通过设置状态项(在这种情况下,将原始按钮的showNewButton中的true设置为onClick,有条件地显示新按钮。

    render() {
        return (
            <div>
                <Button onClick={() => this.setState({ showNewButton: true }))}>Click Me</Button>
                <div id="newBtnSpace">{ this.state.showNewButton && <Button primary id="newBtn">New Button</Button> }</div>
            </div>
        )
    }

PS,您已经成功地弄清楚了如何在jsx中创建Bootstrap按钮:

<Button onClick={NewBSBtnFunc}>Click Me</Button>

0
投票

[onClick不期望返回值,因此返回新按钮将无济于事。

您将事物组织起来的方式非常困难。我建议将您的点击处理程序移到组件中,并用来修改将显示第二个按钮的状态值。

这是我的建议:

import React, { Component } from 'react'
import { Button } from 'reactstrap'

export default class BSBtn extends Component {
  state = {show: false}

  handleClick = () => {
    this.setState({ show: !this.state.show })
  }

  render() {
    return (
      <div>
        <Button onClick={this.handleClick}>Click Me</Button>
        <div id="newBtnSpace">
          {show ? 
            <Button variant="primary" id="newBtn">New Button</Button>
          : null}
         </div>
      </div>
    )
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.