【发布时间】:2014-09-25 05:07:59
【问题描述】:
我有这个 ReactJS 代码来显示一个自定义图像按钮,该按钮在 2 个不同的图像之间切换为 ON 和 OFF 状态。有没有更简单的方法来做到这一点?我希望 CSS 可能是更少的代码行,但找不到一个简单的例子。
下面的代码将状态从<MyIconButton> 传递到<MyPartyCatButton>,然后再传递到<MyHomeView>。我的应用将在主屏幕上有 4 个这样的自定义按钮,这就是我考虑到 <MyIconButton> 的原因。
顺便说一句 - 这是一个移动应用程序,我读过(并且自己注意到了)在移动浏览器上使用复选框真的很慢;这就是为什么我选择不使用复选框来尝试这个。
ReactJS 代码
var MyIconButton = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
console.log("INSIDE: MyIconButton handleSubmit");
// Change button's state ON/OFF,
// then sends state up the food chain via
// this.props.updateFilter( b_buttonOn ).
var b_buttonOn = false;
if (this.props.pressed === true) {
b_buttonOn = false;
}
else {
b_buttonOn = true;
}
// updateFilter is a 'pointer' to a method in the calling React component.
this.props.updateFilter( b_buttonOn );
},
render: function() {
// Show On or Off image.
// ** I could use ? : inside the JSX/HTML but prefer long form to make it explicitly obvious.
var buttonImg = "";
if (this.props.pressed === true) {
buttonImg = this.props.onpic;
}
else {
buttonImg = this.props.offpic;
}
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="image" src={buttonImg}></input>
</form>
</div>
);
}
});
// <MyPartyCatButton> Doesn't have it's own state,
// passes state of <MyIconButton>
// straight through to <MyHomeView>.
var MyPartyCatButton = React.createClass({
render: function() {
return (
<MyIconButton pressed={this.props.pressed} updateFilter={this.props.updateFilter} onpic="static/images/icon1.jpeg" offpic="static/images/off-icon.jpg"/>
);
}
});
//
// Main App view
var MyHomeView = React.createClass({
getInitialState: function() {
// This is where I'll eventually get data from the server.
return {
b_MyPartyCat: true
};
},
updatePartyCategory: function(value) {
// Eventually will write value to the server.
this.setState( {b_MyPartyCat: value} );
console.log("INSIDE: MyHomeView() updatePartyCategory() " + this.state.b_MyPartyCat );
},
render: function() {
return (
<div>
<MyPartyCatButton pressed={this.state.b_MyPartyCat} updateFilter={this.updatePartyCategory}/>
</div>
// Eventually will have 3 other categories i.e. Books, Skateboards, Trees !
);
}
});
【问题讨论】:
-
StackOverflow 不适合“有什么想法吗?”各种问题。 react google 组,或 irc.freenode.net 上的 #reactjs 是解决这类问题的更好地方。
-
我改写了,现在怎么样了?
-
太好了,好多了。我认为它只需要再次重新投票。
标签: javascript css reactjs