在React JS中设置onClick值 [英] Set onClick value in React JS
问题描述
我正在测试,但有一个我无法解决的问题.我基本上想在单击div.btn之前更改onClick值. javascript代码位于react.js中,并且可以在此处使用.我要更改的部分在这里:
I'm currently testing and I have a problem I can not solve. I basically want to change the onClick value from a div.btn before I click on it. The javascript code is in react.js and available here. The part I like to change is here:
React.createElement("div", {className: "img"},
React.createElement("div", {className: "btn noShadow", onClick: this.sendVote.bind(this, this.props.data.candidate1.id)}, this.props.data.translations.vote),
React.createElement("img", {src: domain + this.props.data.candidate1.img_challenge_url, onClick: this.sendVote.bind(this, this.props.data.candidate1.id)})
),
我试图将div.btn.noShadow的值设置为"12345",通常我会在Tampermonkey中执行以下操作:
I am trying to set the value from div.btn.noShadow to "12345", normally I would just do the following in Tampermonkey:
$("#div.content > div.left > div.img > div.btn.noShadow").attr("onclick", "sendVote(12345)")
但这似乎不起作用,因为react.js更改了DOM.我对此还很陌生,不知道如何实现.
But this does not seem to work because react.js changes the DOM. I am fairly new to this and have no idea how to achieve this.
推荐答案
在React哲学中,您希望触发重新渲染(可以通过更改状态来完成),并根据状态/来更改标记/一些条件.
In React philosophy, you would want to trigger a re-render (which can be done by changing the state), and changing the markup based on the state/some condition.
getInitialState: function () {
return {
// ...
fn: this.sendVote.bind(this, this.props.data.candidate1.id)
};
},
render: function () {
return (
// ...
React.createElement("whatever", {
// ...
onClick: this.state.fn
});
);
}
要更改点击回调时:
this.setState({ fn: function blah() {} });
edit: JSFiddle
旁注:
如果组件具有父级,则使用props而不是state是更好的做法.
If the component has a parent, using props rather than state is better practice.
这篇关于在React JS中设置onClick值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!