reactjs - redux-form V6 自定义组件

标签 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>
    );
  }
}

我在我的表单中使用这个组件:

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'}]} />

如何获取所选按钮的值? 我在 redux-form V6 中找不到任何高级示例

onSubmit(data) {
  console.log("onSubmit", data);
}

onSubmit 显示空数据对象

最佳答案

我找到了解决办法

现在我的组件看起来:

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>
    );
  }
}

在表单组件中的用法:

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

<Field name="PODType" component={renderButtonSwitcher} data={[{text: '%', value: 'percent'}, {text: '₽', value: 'amount'}]} />

我找到this discussion这给了我一些想法

关于reactjs - redux-form V6 自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42527132/

相关文章:

reactjs - 使用Redux-Form,如何拥有多个同名输入?

reactjs - Firebase 动态链接不适用于带电容器的 ios

javascript - 保存一个这个。引用

javascript - 更新组件 - React

redux-form - 影响 admin-on-rest 中 CustomField 的整个记录​​值

javascript - redux-form 和 immutable.js

reactjs - 未处理的拒绝提交错误 : Submit Validation Failed

javascript - React.js 子组件不更新从 props 派生的样式,为什么? (样式组件)

javascript - react : Append instead of replacing with render method

reactjs - 在通用 Typescript React 组件上使用 HOC