[英]React dynamically add html element with event handler
Is it possible to append buttons with event handler in react ?是否可以在 react 中添加带有事件处理程序的按钮?
// This is working fine but its pure javascript onclick
, how can I make this element with react js onClick
? // 这工作正常,但它是纯 javascript onclick
,我怎样才能用 react js onClick
制作这个元素?
This is reference code , my scenario is appending html code dynamically这是参考代码,我的场景是动态附加 html 代码
const Button = () => {
const dynamicElement = () => {
let li = document.createElement('li');
li.className = 'dynamic-link'; // Class name
li.innerHTML = "I am New"; // Text inside
document.getElementById('links').appendChild(li);
li.onclick = function(){ alert(0) }
}
useEffect(() => {
dynamicElement();
}, [])
}
You can just convert your function to a functional component like this.您可以将您的功能转换为这样的功能组件。
const DynamicElement = () => {
return (
<li onClick={()=>alert(0)} className="dynamic-link">I am New</li>
)
}
const Button = () => {
const [visible, setVisible] = useState(false);
useEffect(()=>setVisible(true), [])
// if visible is true return <DynamicElement/>, either way return null
return visible ? <DynamicElement/> : null
}
BTW useState
is hooks implementation of a state顺便说一句, useState
是一个状态的钩子实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.