反应-将``this''作为道具传递

时间:2020-09-11 20:10:27

标签: javascript reactjs this

这样做有没有我看不到的副作用?

class App extends React.Component {
    hello() {
        console.log("hello")
    }

    render() {
        return <Layout app={this}>
    }
}

所以稍后我可以从Layout中引用this.props.app.hello(及其他)?

2 个答案:

答案 0 :(得分:2)

这不安全。

React将不知道如何监视更改,因此您可能会错过重新渲染的机会。 React使用===来检查状态更改,即使状态或属性发生更改,App也始终是===App

以这个例子为例:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.setState({text: 'default value'});
    }

    hello() {
        this.setState({...this.state, text: 'new value'});
    }

    render() {
        return (
            <div onClick={this.hello}>
                <Layout app={this}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.app.state.text}</div>
    }
}

当您单击父div时,将调用this.hello,但是子组件将无法检测到状态更新,并且可能无法按预期重新呈现。如果确实重新渲染,那是因为父级做了。依靠它会导致将来的错误。

一种更安全的模式是仅将所需的内容传递给props

class App extends React.Component {
    //...

    render() {
        return (
            <div onClick={this.hello}>
                <Layout text={this.state.text}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.props.text}</div>
    }
}

这将按预期更新。

答案 1 :(得分:-1)

答案

将函数作为道具传递没有错,正如我在您的示例中看到的那样,您唯一要做的就是确保您的函数像下面这样绑定到当前组件 {{ 3}}

参考

example