1

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

我使用 a从组件ref访问组件。ModalApp

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

2 回答 2

2

你通常会传递一个 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>
  )
};
于 2020-05-09T08:23:50.537 回答
1

我尝试了常规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-05-09T08:35:44.570 回答