我有一个表单组件,我想在表单中呈现一个可点击的链接。当人们点击该链接时,子窗体将在弹出窗口中呈现。像这样的东西
class Form extends React.Component{
componentDidMount(){
this.props.loadForm(this.props.url)
}
render(){
const { subfrom, loadSubForm } = this.props;
return(
<form>
<button onClick={()=>loadSubForm(url)}>Load Sub-Form</button>
{ /** Render Parent Form Here ***/ }
{ subform && <Popup><Form url={subform.url} /></Popup> }
</form>
)
}
}
const mapStateToProps = (state) => {
return{
subform:state.getIn(["form",subform"])
}
}
const mapDispatchToProps = (dispatch, props) => {
return{
loadForm: (route)=>{
/** Ajax to load form **/
}
loadSubForm: (route) =>{
dispatch(loadSubForm(route))
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);
加载子窗体时出现错误:
loadForm function is not props of Form
。
答案 0 :(得分:1)
谢谢@Shubham,这是工作。这是解决方案
class Form extends React.Component{
componentDidMount(){
this.props.loadForm(this.props.url)
}
render(){
const { subfrom, loadSubForm } = this.props;
let SubForm = connect(mapStateToProps,mapDispatchToProps)(Form);
/** If you use Redux Form **/
SubForm = reduxForm({})(SubForm);
return(
<form>
<button onClick={()=>loadSubForm(url)}>Load Sub-Form</button>
{ /** Render Parent Form Here ***/ }
{ subform && <Popup><SubForm id="suform" url={subform.url} /></Popup> }
</form>
)
}
}
const mapStateToProps = (state,props) => {
const formid = props.id
return{
subform:state.getIn(["form",formid,subform"])
}
}
const mapDispatchToProps = (dispatch, props) => {
const formid = props.id
return{
loadForm: (route)=>{
/** Ajax to load form **/
}
loadSubForm: (route) =>{
dispatch(loadSubForm(route,formid))
}
}
}
/** If you use Redux Form **/
Form = reduxForm({})(Form);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);
注意:我们需要将表单ID传递给组件和reducer。否则,reducer不知道要听哪种形式,你最终会有一个无限循环。
答案 1 :(得分:0)
对于嵌套组件,您没有传递loadForm或loadSubForm函数,要么为其使用添加条件检查,要么将它们传递下去
class Form extends React.Component{
componentDidMount(){
this.props.loadForm(this.props.url)
}
render(){
const { subform, loadSubForm } = this.props;
return(
<form>
<button onClick={()=>loadSubForm(url)}>Load Sub-Form</button>
{ /** Render Parent Form Here ***/ }
{ subform && <Popup><Form url={subform.url} loadForm={() => {// do something here}} loadSubForm={() => { //whatever you wanna do here}}/></Popup> }
</form>
)
}
}
或
class Form extends React.Component{
componentDidMount(){
this.props.loadForm && this.props.loadForm(this.props.url)
}
render(){
const { subform, loadSubForm } = this.props;
return(
<form>
<button onClick={()=>{loadSubForm && loadSubForm(url)}}>Load Sub-Form</button>
{ /** Render Parent Form Here ***/ }
{ subform && <Popup><Form url={subform.url} /></Popup> }
</form>
)
}
}