簡體   English   中英

如何使用 React 從另一個組件訪問組件的類屬性?

[英]How can I access a component's class properties from another component with React?

如果我創建一個類

 class Foo { constructor(bar) { this.bar = bar; } } let foo = new Foo('baz'); console.log(foo.bar); // baz

我可以毫無問題地訪問.bar屬性。 但是,我將以下代碼拆分為兩個 React 組件(為了清晰起見進行了修剪):

Card組件

class Card extends React.Component {
    constructor(props) {
        super(props);
        this.name = props.cardData.name;
        this.image = props.cardData.image_uris.png;
    }
}

Search組件

class Search extends React.Component {
  constructor(props) {
    super(props);
    this.fuse = null;
    this.state = {
      show: false,
      query: null,
      pool: [
        <Card cardData={{ name: 'test', image_uris: { png: 'https://i.imgur.com/or94i38.jpg' } }}></Card >,
        <Card cardData={{ name: 'test', image_uris: { png: 'https://i.imgur.com/or94i38.jpg' } }}></Card >,
        <Card cardData={{ name: 'test', image_uris: { png: 'https://i.imgur.com/or94i38.jpg' } }}></Card >,
        <Card cardData={{ name: 'test', image_uris: { png: 'https://i.imgur.com/or94i38.jpg' } }}></Card >,
      ],
      results: null
    }

    this.getResults = this.getResults.bind(this);
  }
  componentDidMount() {
    this.fuse = new Fuse(this.state.pool, {
      keys: ['name']
    })

    for (let x of this.state.pool) {
      console.log(x.name); // undefined!
    }
  }

我無法訪問我之前在Card組件上定義的屬性,但我不確定為什么。 我嘗試創建 getter 並將屬性移到構造函數之外,但無濟於事。 我確定我在 React 或 JS 中遺漏了一些簡單的東西,但是什么?

您可以使用可觀察對象(面向服務)在組件之間傳遞數據(屬性值)。 這會將組件屬性值分配給一個對象,然后該對象通過訂閱傳遞給另一個訂閱了該 observable 的組件。

import { Subject } from 'rxjs';

const subject = new Subject();

export const messageService = {
    sendMessage: message => subject.next({ text: message }),
    clearMessages: () => subject.next(),
    getMessage: () => subject.asObservable()
};

然后你的組件代碼:

 componentDidMount() {
        // subscribe to home component messages
        this.subscription = messageService.getMessage().subscribe(message => {
            if (message) {
                //Do stuff if you have the observable content
            } else {
                //Do other stuff is there is no observable content
            }
        });

你不能這樣做。 React 只能將數據傳遞給parent to child但永遠無法將數據從child to parent傳遞child to parent也無法將數據從node to siblings (據我所知)。 因此,您可能會使用 Redux,或者您也可以創建一個全局變量,將其命名為存儲並為該存儲中的組件定義您的屬性。 稍后您將傳遞的任何數據都將引用此全局變量。 但我不認為這是好的做法。 我所知道的正式實用的方法是使用 Redux。

謝謝大家的幫助。 根據 Felix 對我的 OP 的評論,我意識到我的問題是我一般如何考慮 React 中的狀態和數據流。 我傳遞的是組件而不是數據。

我沒有使用 Refs(不正確)或添加新的依賴項,而是選擇通過 state 和 props 將數據傳遞給子組件,然后再渲染數據。

暫無
暫無

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

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