使用ref从另一个组件调用组件方法

我尝试从按钮调用我的Modal组件的show方法。

但这行不通...

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>
        );
    }
}

我使用ref从链接访问Modal组件。

任何的想法 ?

评论
zquam
zquam

通常,您可以通过传递一个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>
  )
};
点赞
评论