8
我有一個與我的應用程序狀態相連的redux-form,並且一切似乎都很好。我可以獲取數據並將其加載到我的表單中,然後提交數據並獲取我想要的元數據...來自外部交互的Redux-Form更新字段值
但是,我有一個自定義交互(顏色選擇器),需要更改託管字段的值蒼蠅。我嘗試的所有東西都會改變屏幕,但不會改變形式狀態,即當我提交表單時,我只是獲取原始字段數據而不是表單中顯示的新數據。
以下版本將字段道具傳遞給組件,並嘗試使用ColorSelect組件狀態作爲字段值。我也嘗試過創建動作創建器,但是相同的結果以及比這個示例更多的代碼...
注意:[email protected]^15.4.2,[email protected]^5.0.2,redux-form @^6.4.3
ES6:CollectionForm.js
...
import ColorSelect from './ColorSelect';
class CollectionForm extends Component {
/**
* On form submit accepted
* @param values
*/
onSubmit(values){
//See screenshot for evidence
log('Updating collection:', 'warn', values);
//values.color is grey and not yellow!
this.props.dispatch(updateCollection(values));
return;
}
/**
* Form render
* @return {JSX}
*/
render()
{
const { handleSubmit, submitting } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field component={renderTextInput} name="name" type="text" label="Name"/>
<Field component={ColorSelect} name="color" />
<div class="field-buttons right-align group">
<Button type="submit" disabled={submitting} primary>
Save
</Button>
</div>
</form>
);
}
};
//Redux form decorator
CollectionForm = reduxForm({ form: 'collectionForm' })(CollectionForm)
// State connector
CollectionForm = connect(
state => ({
initialValues: state.collections.activeCollection
}), //MapStatetoProps
{
onLoad: fetchCollection
} //mapActionToProps
)(CollectionForm);
export default CollectionForm;
ES6:CollectionForm.js
import React, { Component } from 'react'
import { Field, reduxForm, SubmissionError } from 'redux-form';
const colors = [
'grey', 'green', 'yellow', 'orange', 'red', 'purple', 'blue'
];
export default class ColorSelect extends Component {
constructor(props){
super(props);
this.state = {
selectedColor : this.props.input.value //Set to current <Field> input value
};
this.onSelect = this.onSelect.bind(this);
this.renderColor = this.renderColor.bind(this);
}
/**
* Color picker selected
* @param color
*/
onSelect(color){
this.setState({ selectedColor: color }); //Sets correct state here
}
/**
* Render a color list item
* @param color
* @return {JSX}
*/
renderColor(color){
const select = this.state.selectedColor === color ? "active" : "";
const klass = color + " " + select;
return <li key={color}>
<a class={klass} onClick={(event) => this.onSelect(color)}></a>
</li>
}
/**
* Render color list action
* @return {JSX}
*/
render(){
//Override field value with colorSelected state
return (
<div>
<input {...this.props.input} value={this.state.selectedColor} name="color" type="text" label="Color" />
<div class="color-selector">
<ul>
{colors.map((color) => this.renderColor(color))}
</ul>
</div>
</div>
);
}
}
完美!非常感謝你 - 發揮了魅力。 –
@gustavohenke請添加調度包裝 –
這不是必需的:https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-選項 – gustavohenke