【问题标题】:Call a component method from another component with ref使用 ref 从另一个组件调用组件方法
【发布时间】:2020-05-09 08:16:36
【问题描述】:

当用户单击App 组件中的<button> 时,我试图调用我的Modal 组件的show 方法,但它不起作用。

我使用refApp 组件访问Modal 组件。

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.show = this.show.bind(this);
  }

  show() {
    console.log('show');
  }

  render() {
    return (
      <div>...</div>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.modalRef = React.createRef();
  }

  render() {
    return (
      <div>
        <Modal ref={this.modalRef}/>

        <button id="myBtn" onClick={ this.modalRef.show }>
          Call show modal method
        </button>
      </div>
    );
  }
}

【问题讨论】:

    标签: reactjs event-handling modal-dialog react-props react-ref


    【解决方案1】:

    你通常会传递一个 prop 而不是直接在组件上调用一个方法:

    const Modal = ({
      isVisible,
    }) => {   
      useEffect(() => {
        console.log(`The modal has been ${ isVisible ? 'opened' : 'closed' }.`);
      }, [isVisible]);
    
      return (
        <div className={ cx({ ['isVisible']: isVisible }) }>...</div>
      );
    }
    
    const App = () => {
      const [isModalVisible, setIsModalVisible] = useState(false);
    
      const handleButtonClick = useCallback(() => {
        // Toggle the `isModalVisible` value:
        setIsModalVisible(prevIsModalVisible => !prevIsModalVisible);
      }, []);
    
      return (
        <div>
          <Modal isVisible={ isModalVisible } />
    
          <button onClick={ handleButtonClick }>
            { isModalVisible ? 'Close' : 'Open'} Modal
          </button>
        </div>
      )
    };
    

    【讨论】:

      【解决方案2】:

      我尝试使用常规的 ref 方法,它似乎可以与您现有的所有代码一起使用

      class Modal extends React.Component {
        show = () => {
          console.log("show");
        };
      
        render() {
          return <div />;
        }
      }
      
      class App extends Component {
        render() {
          return (
            <div>
              <Modal ref={ref => (this._modal = ref)} />
              <button id="myBtn" onClick={() => this._modal.show()}>
                call show modal method
              </button>
            </div>
          );
        }
      }
      

      演示链接:https://codesandbox.io/s/react-example-z893s?file=/index.js:77-461

      如果这有帮助,请告诉我!

      【讨论】:

      • 别担心,乐于助人!
      猜你喜欢
      • 2020-04-05
      • 2017-08-19
      • 2017-05-19
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多