我有一个包含一组按钮的容器,但让我们仅将组件视为单个组件即可。该组件具有一个onBlockClick,该id接收要去哪里的id

我想将registrationSomeContainer转换为onBlockClick

我的问题是,如何从处理其他容器?

let registrationContainer = ({
    i18n,
    id,
    name,
    representative,
    onBlockClick,
    dispatch
}) => {

    return (
        <div>
            <div
                className="app_wrapper"
            >
                <Block
                    leftIcon="close"
                    lines={[
                        "Some",
                        representative
                    ]}
                    onBlockClick(id)
                />
            </div>
        </div>
    )

}

最佳答案

一种不太有效的方法是

const registrationContainer = ({
    i18n,
    id,
    name,
    representative,
    onBlockClick,
    dispatch
}) => {
    return (
        <div className="app_wrapper">
            <Block
                leftIcon="close"
                lines={[
                    "Some",
                    representative
                ]}
                onBlockClick={onBlockClick.bind(null, id)}
            />
        </div>
    );
}


更优化的代码可能是

const registrationContainer = ({
    i18n,
    id,
    name,
    representative,
    onBlockClick,
    dispatch
}) => {
    return (
        <div className="app_wrapper">
            <Block
                id={id} // Look: passing id
                leftIcon="close"
                lines={[
                    "Some",
                    representative
                ]}
                onBlockClick={onBlockClick} // Look: not binding
            />
        </div>
    );
}

class Block extends Component {
    handleClick = (e) => {
        this.props.onBlockClick(this.props.id);
    };

    render() {
        <div onClick={this.handleClick}>

        </div>
    }
}


为什么绑定不好的方法

绑定onBlockClick={onBlockClick.bind(null, id)}会使onBlockClick每次都获得新的引用,因此导致子组件重新呈现。从这里阅读更多信息https://daveceddia.com/avoid-bind-when-passing-props/

09-25 11:14