简体   繁体   中英

How to pass component to onClick in react

import React from 'react'

export default () => {
  function clickHandler() {
    console.log('Button clicked')
  }
  return (
    <div>
      <button onClick={clickHandler}>Click</button>
    </div>
  )
}

In the above code we see that a function has been passed to the onClick.In the same way to the onClick I need to pass a diffrent component which is present in the same src. This component consists of a.js and a.css file.Could you please help me out with it. Thanks in advance

If you don't mind using classes instead of functions, your other component should look like this:

import React from 'react'

class ShowThisAfterClick extends React.Component {
  return (
    <div>
      <p>This is what you want to show</p>
    </div>
  )
}
export default ShowThisAfterClick

And now you should update the component you've shown:

import React from 'react'
import ShowThisAfterClick from './where/you/put/the/ShowThisAfterClick.js'

class Main extends React.Component {
  constructor(props){
    super(props)
    this.state = { isButtonClicked: false }

    this.clickHandler = this.clickhandler.bind(this)
  }
  
  clickHandler() {
    this.setState({ isButtonClicked: true })
  }
  
  render() {
    const { isButtonClicked } = this.state
    return (
      <div>
        <button onClick={ this.clickHandler }>Click</button>
        { isButtonClicked ? <ShowThisAfterClick /> : ''}
      </div>
    )
  }
}
export default Main

If you want to keep using functions, then I would kindly suggest to read the manual , it is more than well written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM