zby*_*yte 5 javascript reactjs
让我们说我有一个react组件,它将渲染到静态html服务器端。某些元素将具有react不会处理的onsubmit和onclick属性,但仍应调用javascript函数。在这种情况下,我想生成一个联系表单服务器端,但是客户端需要加载recaptcha:
var contactForm = React.createClass({
render: function() {
var recaptcha_id = "recaptcha_div";
return(
<div className="contact pure-form">
<h4 className="boxedTitle">Contact Form</h4>
<form key="form" method="POST" action=".">
<fieldset key="sender_email">
<label>Email</label>
<input name="sender_email" placeholder="Your Email" type="email" />
</fieldset>
<fieldset key="subject">
<label>Subject</label>
<input name="subject" placeholder="Subject" type="text" />
</fieldset>
<fieldset key="message">
<label>Message</label>
<textarea name="message" placeholder="Message"/>
</fieldset>
<fieldset key="humanity">
<div id={recaptcha_id}></div>
<input ref="captcha_btn" type="button" value="Show reCAPTCHA" onClick={"showRecaptcha('"+recaptcha_id+"');"}></input>
</fieldset>
<fieldset key="submit">
<input type="submit" className="btn btn-primary" value="Send"/>
</fieldset>
</form>
</div>
)
}
});
console.log(React.renderComponentToStaticMarkup(contatForm()))
Run Code Online (Sandbox Code Playgroud)
但是不会显示onClick。我尝试了其他一些无效的方法:
我遇到了同样的问题。我的解决方案是使用危险的SetInnerHTML
<td dangerouslySetInnerHTML={{__html: `
<button onClick="alert('hello')" >Detalii</button>
`}}
/>
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你,
onClick 不接受字符串。您需要向它传递一个函数。通常情况下,你可以这样做onClick={window.showRecaptcha.bind(null, recaptcha_id)}。
当然,这不适用于 renderComponentToStaticMarkup。您必须使用 JavaScript(外部或内联<script>标记)绑定事件,或者做一些 hacky 的事情,或者不使用 React。带有 addEventListener 的标签<script>可能是这里最好的解决方案。
五年多来,JavaScript 字符串一直被认为是一种不好的做法。这包括html中的onclick等,eval,带有字符串的setTimeout/setInterval,可能还有一些我忘记了。即使在渲染标记时,这也不是正确的方法。
| 归档时间: |
|
| 查看次数: |
4634 次 |
| 最近记录: |