传递函数,将子状态设置为this.props.children的prop

时间:2017-10-25 09:12:32

标签: reactjs

我需要传递handleClose作为this.props.children的道具。此函数必须访问子状态。我对{handleClose: this.handleClose}有疑问,因为我不明白如何在此处传递参数child

class App extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClose(child) {
        if (child.state.redirect) {
            browserHistory.push(url);
        } else {
            child.setState({showError: false, errorText: ''});
        }
    }

    render() {
        const children = React.Children.map(this.props.children, (child) => {
            return React.cloneElement(child, 
                {handleClose: this.handleClose}, this);
        });

        return (
            <div>
                {children}
            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用参数

传递运行函数的函数

示例

React.cloneElement(child, {handleClose: function () { this.handleClose(child); }.bind(this)}, this);

// OR

React.cloneElement(child, {handleClose: () => this.handleClose(child)}, this);