与redux反应 - 反应评级与redux-form

时间:2017-02-02 12:13:33

标签: javascript reactjs redux

我正在尝试实现一个简单的表单,用户可以在发布评论时为帖子评分。我在github上找到了react-rating,并希望在我的redux-form中使用它。

我放置了StarRating组件

<StarRating onChange={(value) => { this.changeRate("rating", value) } }/>

并隐藏Field在我的表单中,名称设置为"rating"

<Field component="input" type="hidden" name="rating"/>

名为changeRate的函数用于将我的表单中隐藏字段的值更改为点击星星后的值。

changeRate(name, value) {
    this.props.change(name, value) // function provided by redux-form
}

当我第一次点击评级时,输入的值会发生变化,但所选的星星会消失。点击第二次后,星星保持选中状态。

我尝试使用jQuery更改隐藏字段的值。 - 选择星星正常工作但是在发布时,字段值不包含在redux-form中。结合jQuery和change函数可以得到与没有jQuery相同的结果。

可能导致这种情况的原因是什么?

2 个答案:

答案 0 :(得分:4)

首先,您需要一些dynamic props来表示starRating组件中正在变化的星数,而不仅仅是像你那样的onChange回调。这样的事情:

<StarRating 
  onChange={(value) => { this.changeRate("name", value) } }
  initialRate={ this.state.starRating }
/>

您需要调整功能以更改代表星号的本地状态。这样的事情:

changeRate(name, value) {
    this.props.change(name, value) // function provided by redux-form
    this.setState({ starRating: value })
}

答案 1 :(得分:1)

写这个有点晚了,但是做一个自定义组件并在您喜欢的任何地方重用它而不是每次都隐藏Field组件不是更好吗?您可以使用react-star或react-rating。

RenderRatingField.js

//custom Component
import React, {Component} from "react";
import ReactStars from "react-stars";

export class RenderRatingField extends Component {
  render() {
    const {
      label,
      name,
      topTxt,
      starCount,
      input: { value, onChange },
      starSize,
      starsColor,
      meta: { touched, error }
    } = this.props;

    return (
      <div>
        <label>{label}</label>
        <div>
            <label>
              <div className="col-lg-12">
                <h1>{topTxt}</h1>
                <ReactStars
                  count={starCount}
                  value={value === "" ? this.props.initialStars : value}
                  onChange={onChange}
                  size={starSize}
                  color2={starsColor}
                />
              </div>
              {touched && error && <span>{error}</span>}
            </label>
        </div>
      </div>
    );
  }
}

MainComponent.js

//usage
 <Field
  name="myStars"
  initialStars={0}
  starCount={5}
  type="number"
  starSize={24}
  topTxt={'My Stars'} 
  starsColor={"#f00"}
  component={RenderRatingField} />