嗨我想創建一個簡單的表單生成器使用react + redux。如何使用redux動態添加元素
我面臨着從邊欄動態添加元素到容器的問題。
action.js
export const addNewTextBox =() => {
return {
type: 'ADD_NEW_TEXT_BOX'
};
}
export const addNewName =() => {
return {
type: 'ADD_NEW_NAME'
};
}
export const updateChildren = (child) => {
return {
type: 'UPDATE_CHILDREN',
child
};
}
addElementsReducer.js
const initialState = {
addFormElementsVisible: false,
textBoxNum: 0,
nameNum: 0,
childKey: 0,
children: []
}
const addElements = (state = initialState, action) => {
switch (action.type) {
case 'ADD_NEW_TEXT_BOX':
return Object.assign({}, state, {
textBoxNum: state.textBoxNum + 1,
childKey: state.childKey + 1,
});
case 'ADD_NEW_NAME':
return Object.assign({}, state, {
nameNum: state.nameNum + 1,
childKey: state.childKey + 1,
});
case 'UPDATE_CHILDREN':
return Object.assign({}, state, {
children: state.children.concat([action.child])
});
default:
return state
}
}
export default addElements;
上述減速器和動作在這使得側欄和用於添加元素的容器我Layout.js文件傳遞。
Layout.js
<Sidebar
textBoxNum={this.props.textBoxNum}
nameNum={this.props.nameNum}
childKey={this.props.childKey}
updateChildren={this.props.actions.updateChildren}
addNewTextBox={this.props.actions.addNewTextBox}
addNewName={this.props.actions.addNewName}/>
<Create children={this.props.children}/>
從創建我送孩子ElementsContainer.js
<div>
<div className="new_elements">
{(() => {
this.props.children.map((child) => {
return (
<JsxParser
components={[TextBox]}
jsx={child}
/>
);
})
})()}
</div>
</div>
this.props.children
呈現從側邊欄元素的數組。
如何將我的邊欄中的元素推送到childrens數組並將其呈現在我的容器上?
如果這是一個重複的好心指導我的解決方案。如果這還不夠,請讓我知道我可以在我的問題上提供更多的解釋。提前致謝。
這工作。非常感謝 :) – leoc1f3r