簡體   English   中英

如何將 class 組件中的 function 導出到另一個頁面?

[英]How do I export a function in a class component into another page?

當單擊另一個頁面(PageButton.js)上的按鈕時,我想將(Message.js)中的消息文本從“未更新”更改為“已更新”。

消息.js

import React from 'react';
class Message extends React.Component {

    constructor (){
       super()
       this.state = {
           message: 'Not Updated'
        }
    }

    changeMessage(){
        this.setState =({
            message: 'Updated'
        }
        )
    }

  render(){
    return (
      <h1>{this.state.message}</h1>
      )
    }
  }

export default Message

頁面按鈕.js

import React from 'react';
import { changeMessage } from "./Message"; //this does not work
import Message from "./Message"; //this does not work too

class Pagebutton extends React.Component {

    render(){

        return (
           <div>
               <button onClick={()=>this.changeMessage()}>Change Text</button>

           </div>
           
        )
    }
}

export default Pagebutton;

在 Pagebutton.js 中,'changeMessage' 沒有定義,我該如何讓它工作? 如果這種導入函數的方法不正確,請教我另一種方法:)

非常感謝您的幫助!

您不能在 javascript 中的函數或類中導出內容。 為了獲得訪問權限,您必須將changeMessage作為propMessagePagebutton都是其后代的組件傳遞。 請參閱: https://reactjs.org/docs/components-and-props.html

一個示例設置是:

容器.js

import React from 'react';
import Pagebutton from "./Pagebutton";
import Message from "./Message";

class Container extends React.Component {

    constructor (){
       super()
       this.state = {
           message: 'Not Updated'
        }
    }

    changeMessage(){
        this.setState =({
            message: 'Updated'
        }
        )
    }

  render(){
    return (
      <Message message={this.state.message} />
      <Pagebutton changeMessage={this.changeMessage.bind(this)} /> 
      )
    }
  }

export default Container

頁面按鈕.js

import React from 'react';

class Pagebutton extends React.Component {

    render(){

        return (
           <div>
               <button onClick={()=>this.props.changeMessage()}>Change Text</button>

           </div>
           
        )
    }
}

export default Pagebutton;

消息.js

import React from 'react';
class Message extends React.Component {


  render(){
    return (
      <h1>{this.props.message}</h1>
      )
    }
  }

export default Message

除了@Kyruski 的回答之外,您還可以使用 Context API,它可以“神奇地傳遞道具”。

https://reactjs.org/docs/context.html

文檔有很多例子,你可以試試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM