假设我有包含输入字段的组件A.第二个组件B包含一个提交按钮 . 这两个组件没有直接链接(例如,它们是2个深度树中的2个叶子)
在提交时我需要检索输入值,如何在react redux环境中解决这个问题?
我想到的最明显的解决方案是将React Component的refs绑定到redux状态,这样状态就会引用输入值(通过state.fieldName.input.value访问) .
在提交按钮组件中(记住它与输入组件没有直接关系),mapStateToProps返回onClick prop,它是一个可以访问状态的函数,从而可以访问输入值并可以执行“不纯”作业(例如db请求)
所以我的代码应该是这样的:
//components/TestForm.jsx
class TestForm extends Component {
render() {
return <FormInput
ref={(ref) => this.props.registerFormField(ref)}
value=...
...
/>
}
}
//redux/actions/index.js
const registerFormField = (field) => {
return {
type: ActionTypes.REGISTER_FORM_FIELD,
field: field
}
}
//redux/reducers/index.js
const rootReducer = (state = {}, action) => {
switch (action.type) {
case ActionTypes.REGISTER_FORM_FIELD:
var newState = {...state};
newState[action.field.input.name] = action.field.input;
return newState
default:
return state
}
}
//containers/SubmitButton.js
const mapStateToProps = (state, ownProps) => {
return {
text: "Submit",
onClick: () => {
//do your impure job with state.fieldName.value
}
}
}
const SubmitButton = connect(
mapStateToProps,
mapDispatchToProps
)(FormSubmitButton)
//components/FormSubmitButton.jsx
class FormSubmitButton extends Component {
render() {
return <button
onClick={this.props.onClick}
>
{this.props.text}
</button>
}
}
我简要地阅读了redux-form文档,它似乎无法绑定两个不相关的组件,如上所述(也许我错了;))
有没有其他正确/优雅的解决方案来解决这个问题?
1 回答
在这种情况下,无需使用
ref
.惯用方法是通过提供
value
属性将表单字段创建为controlled components . 这可以从全局状态(映射在mapStateToProps
中)提供,也可以从公共父组件的状态提供 .您还需要听取输入的更改 . 为此,为
input
的onChange
道具提供处理程序 . 然后,此处理程序应在redux存储或组件状态中更改表单数据,具体取决于您采用的方法 .这样,只要它可以访问表单数据,在您的响应应用程序中放置提交按钮等的位置无关紧要 .
有关用例的工作示例,have a look at this JSBin . 这演示了如何将表单分成多个组件,并将输入值保留在redux存储中,而不依赖于
ref
.