如何在reactjs

时间:2019-09-16 10:57:56

标签: reactjs next.js

我试图使用refs从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中是否还有其他选择。请帮助

1 个答案:

答案 0 :(得分:3)

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