redux-form V6自定义组件

MrD*_*uDu 4 reactjs redux-form

我想为redux-form V6创建自定义组件.它看起来像按钮切换器.

零件

import React, { Component } from 'react';

export default class ButtonSwitcher extends Component{
// props.buttons [{text: "Btn Text", value: "BtnValue"}]
  render (){
    return (
      <div className="btn-group" style={{verticalAlign: 'top'}}>
        {this.props.buttons.map((button, index)=>(
          <a href="#" key={index} onClick={this.props.onChange} className={(this.props.value === button.value) ? 'active btn btn-default' : 'btn btn-default'}>{button.text}</a>
        ))}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我在我的表单中使用此组件:

const renderButtonSwitcher = props => {
  return (
    <ButtonSwitcher value={props.input.value} onChange={props.input.onChange} buttons={props.data} />
  )
};

<Field name="PODType" component={renderButtonSwitcher} data={[{text: '%', value: 'percent'}, {text: '$', value: 'amount'}]} />
Run Code Online (Sandbox Code Playgroud)

我怎么能得到选定的按钮值?我找不到redux-form V6的任何高级示例

onSubmit(data) {
  console.log("onSubmit", data);
}
Run Code Online (Sandbox Code Playgroud)

onSubmit 显示空数据对象

MrD*_*uDu 5

我找到了解决方案

现在我的组件看起来:

import React, { Component } from 'react';

export default class ButtonSwitcher extends Component{
  // props.buttons [{text: "Btn Text", value: "BtnValue"}]

  onClick(value){
    this.props.onChange(value);
  }

  render (){
    return (
      <div className="btn-group" style={{verticalAlign: 'top'}}>
        {this.props.buttons.map((button, index)=>(
          <a href="#" key={index} onClick={this.onClick.bind(this, button.value)} className={(this.props.value === button.value) ? 'active btn btn-default' : 'btn btn-default'}>{button.text}</a>
        ))}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

表单组件中的用法:

const renderButtonSwitcher = props => {
      return (
        <ButtonSwitcher {...props.input} buttons={props.data} />
      )
    };

<Field name="PODType" component={renderButtonSwitcher} data={[{text: '%', value: 'percent'}, {text: '?', value: 'amount'}]} />
Run Code Online (Sandbox Code Playgroud)

我找到了这个讨论,并给了我一些想法