简体   繁体   English

react.js 将值传递给子函数

[英]react.js pass value to child function

I'm trying to create a Map with overlays, in react.js: Inside render , I got this:我正在尝试在 react.js: inside render创建一个带有叠加层的地图,我得到了这个:

<Map
                    provider={providers.osm}
                    defaultCenter={[22.3402092,91.8124206]}
                    center={[22.3402092,91.8124206]} zoom={this.state.zoom}
                    width={window.innerWidth*.8} height={window.innerHeight*.8}>

                    {
                        this.line()
                    }

                </Map>

And my line looks like this:我的line如下所示:


    line = ({ mapState: { width, height }, latLngToPixel,  style = { stroke: 'rgb(255,0,0)', strokeWidth: 2 } }) => {

        let coordsArray=this.state.vertex;

        if (coordsArray.length < 2) {
            return null;
        }

        let lines = [];
        let pixel = latLngToPixel(coordsArray[0]);




        for (let i = 1; i < coordsArray.length; i++) {
            let pixel2 = latLngToPixel(coordsArray[i]);
            lines.push(
                <line key={i} x1={pixel[0]} y1={pixel[1]} x2={pixel2[0]} y2={pixel2[1]} style={style} />
            );
            pixel = pixel2;
        }

        return (
            <svg width={width} height={height} style={{ top: 0, left: 0 }}>
                {lines}
            </svg>
        )
    }

It says Cannot read property 'mapState' of undefined , how can I resolve this?它说无法读取 undefined 的属性“mapState”,我该如何解决?

codesandbox.io 代码和盒子.io

You don't pass arguments to this.line so mapState will always be undefined您不向 this.line 传递参数,因此 mapState 将始终未定义

In this line ({ mapState: { width, height }, you are destructuring the mapState from the argument. Since you don't pass anything to this.line() it will always be undefined.在这一行中({ mapState: { width, height },您正在从参数中解构 mapState。由于您没有将任何内容传递给this.line()因此它始终是未定义的。

To pass props to this.line() just add what ever arguments you want in the brackets this.line(this.props) .要将道具传递给this.line()只需在括号this.line(this.props)添加您想要的任何参数。

But passing the props from the Map to the line is not possible unless map has some hidden context you can check.但是将道具从地图传递到线是不可能的,除非地图有一些可以检查的隐藏上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM