首页 > 解决方案 > 如何将变量从一个组件传递到另一个组件

问题描述

我知道这个问题看起来多余,我有一个不同的问题,我无法在这里找到它。

我想要一个函数返回一个 Id,并且我必须将该 Id 传递给另一个组件

如果你想要完整的代码,这里是 https://codesandbox.io/s/qz7n1yy06j

主页.js

onEditClick(objectId){
        return <EditRow objectId={objectId}/>
    }

仅供参考,我在主页中尝试了 Console,它具有正确的值,但是当它传递给 editrow 时,它变得未定义。

编辑行.js

   class EditRow extends React.Component{

    renderTextField(field){
        return(
            <div className="form-group">
                <label>{field.label}</label>
                <input
                    className="form-control"
                    type="text"
                    placeholder={field.placeholder}
                    {...field.input}
                    required
                />
            </div>
        )
    }

    onSubmit(values){
        this.props.editRow(values, () => {
            this.props.history.push('/login_success');
        },this.props.objectId);
    }

    render(){
        const {handleSubmit}=this.props;

        return(
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
                <Field
                    label={"Student Name"}
                    placeholder={"Enter the Name"}
                    name="name"
                    component={this.renderTextField}
                />
                <Field
                    label={"Average Grade"}
                    placeholder={"Enter the Average grade"}
                    name="avgGrade"
                    component={this.renderTextField}
                />
                <Field
                    label={"Curriculum / Occupation"}
                    placeholder={"Enter the Curriculum or Occupation"}
                    name="occupation"
                    component={this.renderTextField}
                />
                <button className="btn btn-primary btn-right">Edit</button>
            </form>
        );
    }
}

export default reduxForm({form:'EditRow'})(connect (null,{editRow})(EditRow));

我试图在提交表单时将值传递给组件。我浏览了这个并没有得到。真正的帮助会很好。所以请在给减分之前给我答案。谢谢

标签: reactjsreact-redux

解决方案


由于您react-route在单击编辑按钮时使用路由来编辑页面,因此您不需要返回editrow组件,因为新组件的渲染由 . 负责react-router Link,因此您需要将 objectId 作为参数传递为

 <Link to={"/login_success/editdetails/" + this.props.row.objectId}>
        <button className="edit">
              Edit
        </button>    
 </Link>

在路线中,您需要将参数提及为

 <Route path="/login_success/editdetails/:objectId" component={EditRow} />

然后您可以访问editrow组件中的参数为

this.props.match.params.objectId 

推荐阅读