[英]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.