在反应中向父母提交参数的正确方法

时间:2018-08-13 12:55:46

标签: javascript reactjs

很抱歉我可能会犯任何语言错误。我不是母语人士

我有一个react组件,该组件从API提取数据,然后使用entrys.map函数使用这些条目填充表:

 render() {
    return (
        <div>
            <table>
                <thead>
                <tr>
                    <td>ID</td>
                    <td>username</td>
                    <td>name</td>
                </tr>
                </thead>
                <tbody>
                {this.state.users.map(user => <User key={user.userID} user={user} onClick={this.doSomething}/>)}
                </tbody>
            </table>
        </div>
    );
}

然后,在子组件用户User中,我从API返回数据,还返回了两个按钮,单击这些按钮应调用父函数的doSomething函数。

我一直在寻找一种方法来调用该函数,并且还发送参数,例如它所在的行以及单击了两个按钮中的哪个按钮。

我使用.bind()函数进行了尝试,该函数将所需的参数发送到该函数,但不是该函数所在的行,而且我无法在父组件中设置State,因为this引用了我已发送的参数。

<input type='button' className='btn btn-xs btn-info' onClick={this.props.changeState.bind("week")}/>

所以我现在的问题是,如果可以的话,如何正确地将数据发送回父级。

3 个答案:

答案 0 :(得分:2)

在您的User组件中,您可以使用bind这样的方式传递数据

<input type='button' className='btn btn-xs btn-info' onClick={this.props.onClick.bind(this, "pass the row data here")}/>

在您的父组件中,功能将如下所示

doSomething = (data) => { // use arrow function
  console.log(data) // should appear pass the row data here
}

答案 1 :(得分:1)

首先,您需要将父级绑定到doSomething函数

<User ... changeState={this.doSomething.bind(this)}/>

然后,在子元素中,您可以像这样将参数传递给函数:

<input ... onClick={() => this.props.changeState("week")}/>

在子元素中,this.props.changeState是父级的doSomething函数,其上下文设置为父级(.bind(this)

答案 2 :(得分:0)

据我对您的问题的理解,每个用户行中都有两个按钮,您必须传递用户单击了哪个按钮和哪个行。为此,请按照下列步骤操作:

步骤1:在父级中创建两个函数并将其绑定到父级构造函数中。 第2步:将这些功能作为道具传递给子组件,并在相应按钮的onClick上使用它们。

例如 父组件:

class Parent extends Component {
        constructor(props) {
            super(props);
            this.clickButton1 = this.clickButton1.bind(this);
            this.clickButton2 = this.clickButton2.bind(this);
        }

        clickButton1(row) {

        }

        clickButton2(row) {

        }

        render () {
            return (
                <User 
                    key={user.key}
                    clickButton1={this.clickButton1}
                    clickButton2={this.clickButton2} 
                />
            )
        }
    }

子组件:

    class User extends Component {

        render() {
            const { key, clickButton1, clickButton1 } = this.props;
            <button onClick={ ()=> clickButton1(key) }>
                Button 1
            </button>
            <button onClick={ ()=> clickButton2(key) }>
                Button 2
            </button>
        }
    }

在这里,我们将键作为参数传递给函数,您还可以获得单击的按钮。