[英]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.在上面的代码中,我们看到 function 已传递给 onClick。以与 onClick 相同的方式,我需要传递存在的相同组件。 This component consists of a.js and a.css file.Could you please help me out with it.
该组件由 a.js 和 a.css 文件组成。请您帮我解决一下。 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.如果您想继续使用功能,那么我建议您阅读手册,它写得非常好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.