传递函数作为React组件之间的道具

时间:2018-03-12 14:53:19

标签: reactjs

大家好!请有人帮我解释一下这个的错误 hideOrderDetailsAndDarkOverlay = {()=> this.hideOrderDetailsAndDarkOverlay()} 。因为我有一个错误无法读取属性' hideOrderDetailsAndDarkOverlay'未定义

class OrderBlockTemplate extends Component {
constructor(props) {
    super(props);
    this.showOrderDetailClick = this.showOrderDetailClick.bind(this);
    //...other code
    this.state = {
        showOrderDetails : false,
        orderData : orderFullData,
        showDarkOverlay : false
    };
}

showOrderDetailClick() {
    let {showOrderDetails} = this.state;
    this.setState({
        showOrderDetails : !showOrderDetails,
        showDarkOverlay : true
    });
}

hideOrderDetailsAndDarkOverlay() {
    this.setState({
        showOrderDetails : false,
        showDarkOverlay : false
    });
}

render() {
    return (
        <div className="container-fluid orderBlockTemplate">
            <div className="orderBlockWrapper">

                {/* other code */}

            </div>

            {/*Show DarkOverlay Component if "orderBlockDetailButton" is clicked*/}
            {this.state.showOrderDetails ? <DarkOverlay/> : ""}

            {/*Show OrderDetails Component if "orderBlockDetailButton" is clicked.
            And transfer order data into OrderDetailsBlock*/}
            {this.state.showOrderDetails ? 
                this.state.orderData.map(function(item, i) {
                    return(
                        <OrderDetails key={i} 
                                    item={item}
                                    hideOrderDetailsAndDarkOverlay={() => this.hideOrderDetailsAndDarkOverlay()}
                        />
                    );
                }) : ""
            }                

        </div>

    );        
}
}

export default OrderBlockTemplate;

1 个答案:

答案 0 :(得分:2)

您在此行中丢失了对this右侧的引用:

this.state.orderData.map(function(item, i) {

您可以将其更改为使用胖箭头来保留它:

this.state.orderData.map((item, i) => {

或者明确地将this作为第二个参数传递给orderData.map:

this.state.orderData.map(function(item, i) {
    // ...
}, this)

Array.prototype.map() docs解释了这种行为。

请记住,你不需要一个胖箭头:

hideOrderDetailsAndDarkOverlay={() => this.hideOrderDetailsAndDarkOverlay()}

您可以通过构造函数中的绑定来避免它:

constructor() {
    // ...
    this.hideOrderDetailsAndDarkOverlay = this.hideOrderDetailsAndDarkOverlay.bind(this);
}

或者通过使用胖箭头声明该函数:

hideOrderDetailsAndDarkOverlay = () => {

使用这两种方法中的任何一种都可以编写:

hideOrderDetailsAndDarkOverlay={this.hideOrderDetailsAndDarkOverlay}

这意味着每次调用render时都不会创建新的匿名函数。