2017-03-01 51 views
3

我想爲redux-form V6創建自定義組件。它看起來像按鈕切換器。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'}]} /> 

如何我可以選擇按鈕的價值? 我無法找到終極版型V6任何先進典型,

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

onSubmit顯示空數據對象

回答

1

的方式,你正在做的是不一樣終極版形式的作品。 <Field />組件是所有各種html表單字段的包裝,如<input />,<textarea />等。

這些字段有一個namevalue屬性,它在表單中以及通過還原形式使用。

您正在渲染<a />,它們是簡單的鏈接,因此redux-form無法獲取/設置它們的值。

要從這些鏈接中獲取值,您需要解決,可能使用隱藏字段,點擊此鏈接時會更新該隱藏字段。

3

我找到解決辦法

現在我的組件看起來:

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這給了我一些想法