reactjs如何从父组件访问子组件的方法

How to access method of the child component from parent in reactjs

我正在尝试使用 refs.but 在 reactjs 中从父组件调用子组件,当我尝试调用时它抛出错误提示 showModal() 不是函数。

//app.js

 class app extends Component {
      constructor(props) {
         super(props);

         this.POPUP = React.createRef();
      }
      showModal(){
            this.POPUP.showModal(true);
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={() => this.showModal()}>Show</a></span>

                <POPUP onRef={ref => (this.POPUP = ref)}></POPUP>
             </React.Fragment >
       )
     }
 }

popup.js

 class POPUP extends Component {
   showModal(show) {
         console.log('showmodal');

     }
   render() {
          console.log(this.props.showModalPopup);
       <React.Fragment>
             <Modal

                 position="center">
                 <div>
                     //code
                 </div>
             </Modal>
       </React.Fragment>
       )
     }
 }

nextjs.please 帮助

中是否有其他选择

https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

首先,如果您想访问那个 POPUP 实例,您应该这样做

this.POPUP.current.showModal(true);

顺便说一句,如果您打算更改其状态,您的 showModal 函数需要绑定到子组件。

然而,即使这样也是可行的 - 这通常不是推荐的做法 React

如果您希望父级决定 showModalPopup 是否应该为真,您可能应该将状态保留在父级组件中:

 class App extends Component {
      constructor(props) {
         super(props);

         this.state = { showModalPopup: false };

         this.showModal = this.showModal.bind(this);
      }
      showModal(){
            this.setState({ showModalPopup: true });
      }
      render() {
         return (
             <React.Fragment>
                <span><a onClick={this.showModal}>Show</a></span>

                <POPUP show={this.state.showModalPopup}></POPUP>
             </React.Fragment >
       )
     }
 }
const POPUP = ({ show }) => (
    <Modal show={show} position="center">
      // your content.
    </Modal>
)