<div onClick={(event) => this.addToCart(event)}>
<ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml />
</div>
I have situation like in the code. I'm rendering button and I want to add on click event on that rendered button. this.props.customButton has value '<button>Test</button>'
. Obviously this is not a good way to add onClick event to rendered button. I'm get the button in my app, but when I click on button my program fails. Does anyone help me?
You could use React.cloneElement
to create a new button from the existing one with the added onClick
handler, then pass it to ReactMarkdownWithHtml
.
render() {
const handleClick = (event) => this.addToCart(event)
const buttonWithClickHandler = React.cloneElement(this.props.customButton, { onClick: handleClick }
return (
<ReactMarkdownWithHtml children={buttonWithClickHandler} allowDangerousHtml />
)
}
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.