【发布时间】:2017-08-22 17:18:03
【问题描述】:
我正在尝试使用 React、Redux Form 和 Bootstrap (reactstrap) 创建一个可切换按钮组。
我所做的已经正确地更新了 redux 表单数据。
问题在于按钮颜色属性应该在“成功”和“次要”之间切换。现在它确实在第一次切换时设置了颜色,但是当我之后单击另一个按钮时它不会更新。
这是我的渲染组件:
import React from 'react';
import classNames from 'classnames';
import { Label, FormGroup, ButtonGroup, Button } from 'reactstrap';
import FontAwesome from 'react-fontawesome';
export default class buttonOptions extends React.PureComponent {
static propTypes = {
input: React.PropTypes.object,
buttons: React.PropTypes.any,
label: React.PropTypes.string,
meta: React.PropTypes.shape({
touched: React.PropTypes.bool,
error: React.PropTypes.any,
})
};
constructor(props) {
super(props);
this.toggleOption = this.toggleOption.bind(this);
}
toggleOption(val) {
if (!this.props.input.value.length) this.props.input.value = [];
// option per buttongroud is always limited to 1
// remove previously selected options
for (let b of this.props.buttons) {
if (b.value !== val && this.props.input.value.indexOf(b.value) > -1) {
this.props.input.value.splice(this.props.input.value.indexOf(b.value), 1)
}
}
// push the new option and update state
this.props.input.value.push(val);
this.props.input.onChange(this.props.input.value)
}
render() {
const { input, buttons, label, meta: { touched, error }} = this.props;
const labelStyles = {width: '100%', marginBottom: '0'};
return (
<FormGroup>
<Label style={labelStyles}>{label}</Label>
<ButtonGroup>
{
buttons.map((b) => {
return (
<Button
key={b.title}
color={classNames({
success: input.value.indexOf(b.value) > -1,
secondary: input.value.indexOf(b.value) === -1,
})}
role="button"
onClick={() => { this.toggleOption(b.value) }}
>
{b.title}
</Button>
)
})
}
</ButtonGroup>
</FormGroup>
);
}
}
这就是它的实现方式:
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './AdWizard.css';
import cx from 'classnames';
import FontAwesome from 'react-fontawesome';
import { Field, reduxForm } from 'redux-form'
import { Row, Col, FormGroup, Label, Button } from 'reactstrap';
import buttonOptions from '../FormComponents/buttonOptions';
class Step2 extends React.Component {
constructor(props) {
super(props);
this.workingtimes = [
{
title: "Vollzeit",
value: "Vollzeit",
selected: true
},
{
title: "Teilzeit",
value: "Teilzeit",
selected: false
}
]
}
render() {
const { handleSubmit, previousPage } = this.props;
return (
<form onSubmit={handleSubmit}>
<Row className="justify-content-center">
<Col xs="12" sm="6">
<Field
label="Arbeitszeit"
name="arbeitszeit"
buttons={this.workingtimes}
component={buttonOptions}
/>
</Col>
</Row>
</form>
)
}
}
Step2 = reduxForm({
form: 'posting',
destroyOnUnmount: false,
forceUnregisterOnUnmount: true
})(Step2);
export default withStyles(s)(Step2);
如果有人能帮忙就太好了!
干杯 斯蒂芬
【问题讨论】:
标签: reactjs react-redux redux-form