【问题标题】:How do I assign a function to a button from another component in React?如何将功能分配给 React 中另一个组件的按钮?
【发布时间】:2021-10-09 18:15:43
【问题描述】:

我有一个Map 组件,我在其中创建了一个函数来获取用户的当前位置。我已将此地图组件导入到更大的RetailLocations 组件中。我想将Map 组件中创建的handleClick() 函数分配给RetailLocations 组件中的按钮。相关代码:

Map Component code:

    const [center, setCenter] = useState({ lat: 0, lng: 0 });
    const location = useGeoLocation();
    const mapRef = useRef();
    
    const ZOOM_LEVEL = 20;

    

    const handleClick = (e) => {
        if (location.loaded) {
            mapRef.current.leafletElement.flyTo(
                [location.coordinates.lat, location.coordinates.lng],
                ZOOM_LEVEL,
                { animate: true }
            );  
        } 
    };



    return <>
        <MapContainer
            center={center}
            zoom={ZOOM_LEVEL}
            ref={mapRef}
            scrollWheelZoom={false}
            className={style.mapContainer}
        >
            <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
            {location.loaded && (
                <Marker position={[ location.coordinates.lat, location.coordinates.lng ]}></Marker>
            )}
        </MapContainer>
    </>;
};

export default Map;

This is the RetailLocations component's relevant code:

import Map from './Map';
....
<button
    className={style.locationBtn}
    onClick={handleClick}
>My Location</button>
....

我还有什么遗漏的吗?

【问题讨论】:

  • 我觉得这是Map 组件可能应该订阅某些事件源(例如可观察对象)的情况之一,该事件源会发出坐标,然后您只需从应用中的其他地方。
  • 组件不能返回额外的变量。但是为什么不简单地将 handleClick 逻辑移动到RetailLocations

标签: javascript reactjs onclick event-handling


【解决方案1】:

你应该阅读这个。来自复数观点:组件是 React 不可或缺的一部分。每个 React 应用程序由几个组件组成,每个组件可能需要触发各种操作的用户交互。 为了实现用户交互,我们可以调用函数和方法来完成 React 中的特定操作。我们使用这些操作将数据从父组件传递到子组件或子组件到父组件。 https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component

【讨论】:

    【解决方案2】:

    使用 forwardRef 和 useImperativeHandle 钩子访问功能组件内的方法。

    地图组件:

    import { forwardRef, useImperativeHandle } from 'react'
    
    const Map = forwardRef((props, ref) => {
      ...
    
      const handleClick = (e) => {
          if (location.loaded) {
              mapRef.current.leafletElement.flyTo(
                  [location.coordinates.lat, location.coordinates.lng],
                  ZOOM_LEVEL,
                  { animate: true }
              );  
          } 
      };
    
      useImperativeHandle(
        ref,
        () => ({ handleClick }),
        [handleClick]
      );
    
      return <>
         <MapContainer
             center={center}
             zoom={ZOOM_LEVEL}
             ref={mapRef}
             scrollWheelZoom={false}
             className={style.mapContainer}
         >
             <TileLayer
                 attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                 url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
             />
             {location.loaded && (
                 <Marker position={[ location.coordinates.lat, location.coordinates.lng ]}></Marker>
             )}
         </MapContainer>
      </>;
    })
    

    RetailLocations 组件:

    import Map from './Map';
    import { useRef } from 'react';
    ....
    
    const RetailLocations = () => {
    
       const ref = useRef()
       
       return <>
         <Map ref={ref} />
         <button 
             className={style.locationBtn}
             onClick={(e) => ref.current.handleClick(e)}>
           My Location
         </button>
       </>
    }
    
    ....
    

    【讨论】:

    • 谢谢。唯一需要注意的是现在我收到此错误:警告:无法为函数组件提供参考。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef()
    猜你喜欢
    • 2013-12-28
    • 2021-05-16
    • 2021-06-30
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多