我需要一个具有 3 种状态的按钮。
每个状态都需要处理点击并发送一个值。
用例是:
- 不喜欢
- 收藏
- super 喜欢
我尝试使用 this.state.count + 1
来指示级别,但没有成功。我不确定这也是最好的方法。
我使用 const fill
作为 CSS 值(颜色),我将传递给 svg
元素。
这是我的尝试,但它受到限制,因为 checked
只有 2 个状态(开/关),我需要 3 个。它也在 this codepen 中.
class Switch extends React.Component {
constructor ( props ) {
super( props );
this.state = {
checked: !!props.checked
};
}
handleClick(e) {
this.setState({
checked: !this.state.checked
});
}
render () {
const fill = this.state.checked ? "#E1E0DD" : "#999999";
return (
<button className="switch" onClick={this.handleClick.bind(this)} >
<svg width="100" height="100">
<g>
<path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
</g>
</svg>
</button>
);
}
}
const App = () => (
<div>
<Switch checked={ true } />
</div>
)
React.render( <App />, document.getElementById( "page" ) );
最佳答案
您的代码存在多个问题。
首先,不要从其 props 派生组件的状态 - 这是一种反模式。
其次,因为 React 可以批处理 setState 调用,所以你应该使用 function(prevState, nextProps)
当您将新状态基于先前状态时,setState 的参数而不是对象。
第三,如上面的评论所述,您永远无法通过使用 bool 值获得三种状态。
我会像这样实现它:
class TripleSwitch extends React.Component {
constructor() {
super();
this.state = {
favourite: 0
}
}
handleClick() {
this.setState((prevState) => ({
favourite: (prevState.favourite + 1) % 3
}));
}
render () {
const { favourite } = this.state;
const fill = favourite === 0 ? "#E1E0DD" :
favourite === 1 ? "#000444" :
"#999999";
return (
<button className="switch" onClick={this.handleClick.bind(this)} >
<svg width="100" height="100">
<g>
<path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
</g>
</svg>
</button>
);
}
}
关于javascript - 使用 React 的具有 3 个状态的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082797/