简体   繁体   English

反应,从 const 组件子项设置父项的 const 组件变量

[英]react, set const component variable of a parent from a const component child

I'm new to react and I have a question that maybe is simple but I couldnt figure it out yet.我是新手,我有一个问题可能很简单,但我还想不通。

I have a const component parent that calls a const component child, what I want is to pass values from the parent to the child, and if the values are edited in the child the parent has access to the edited value.我有一个调用 const 组件子级的 const 组件父级,我想要的是将值从父级传递给子级,如果在子级中编辑了值,则父级可以访问编辑后的值。

What I want is this, the following const component is the child, it just render a map and if you click it set the const selectedPosition with longitude and latitude, I want that the const component parent passes an intial value of longitude and latitude and everytime its edited in the child the parent get the value:我想要的是这个,下面的 const 组件是子组件,它只是渲染一个 map 并且如果你点击它设置 const selectedPosition 和经度和纬度,我希望 const 组件父级每次都传递一个经度和纬度的初始值它在孩子中编辑,父母得到值:

    import React from 'react'
    import {MapContainer, Marker,TileLayer,Popup, useMapEvents } from 'react-leaflet'
    import 'leaflet/dist/leaflet.css'   
    
    
    const MapView = () =>{
    
        const [initialPosition, setInitialPosition] = React.useState([0,0]);
        const [selectedPosition, setSelectedPosition] = React.useState([0,0]);
    
    
       
        
        const Markers = () => {
        
            const map = useMapEvents({
                click(e) {                                
                    setSelectedPosition([
                        e.latlng.lat,
                        e.latlng.lng
                    ]);              
                },            
            })
        
            return (
                selectedPosition ? 
                    <Marker           
                    key={selectedPosition[0]}
                    position={selectedPosition}
                    interactive={false} 
                    />
                : null
            )   
            
        }
    
        
    
        return <MapContainer center={selectedPosition || initialPosition} zoom={5}   
                             
                style={{height:"200px",width:"500px"}}>
            <TileLayer url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
             ></TileLayer>
             <Markers />
        </MapContainer>
    }
    
    export default MapView

The const component parent is something like this: const 组件父级是这样的:

    const Locations = () => {
    
    ....
    
    return (
      <MapView />
    )
    
    }

How could I achive this?我怎么能做到这一点? Is this the correct way of doing this or should I use class components?这是这样做的正确方法还是我应该使用 class 组件? Thanks!谢谢!

You can use useState in the parent and pass it down to the children.您可以在父级中使用 useState 并将其传递给子级。

Example:例子:

Location (parent)位置(父)

const Locations = () => {

const [myState, setMyState] = useState("something")

return (
  <MapView setMyState={setMyState}/>
)

MapView (children)地图视图(儿童)

   const MapView = ({setMyState}) => {

    
     const handleClick = () => {
       setMyState("something else")
     }
    
     return (
       <button onClick={handleClick> click </button>
     )
}

In a react way,you are supposed hoist the props up to the parent component.Hope this will be helpful!以一种反应的方式,您应该将道具提升到父组件。希望这会有所帮助!

const MapView = ({selectedPosition,setSelectedPosition}) =>{

const Markers = () => {

    const map = useMapEvents({
        click(e) {                                
            setSelectedPosition([
                e.latlng.lat,
                e.latlng.lng
            ]);              
        },            
    })

    return (
        selectedPosition ? 
            <Marker           
            key={selectedPosition[0]}
            position={selectedPosition}
            interactive={false} 
            />
        : null
    )   
    
}



return <MapContainer center={selectedPosition} zoom={5}   
                     
        style={{height:"200px",width:"500px"}}>
    <TileLayer url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
     ></TileLayer>
     <Markers />
</MapContainer>

} }

const Locations = () => {
const [selectedPosition, setSelectedPosition] = React.useState([0,0]);

return (
  <MapView selectedPosition={selectedPosition} setSelectedPosition={setSelectedPosition} />
)

} }

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

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