【问题标题】:child of the component "this" value and how do I get to parent component?组件“this”值的子组件以及如何访问父组件?
【发布时间】:2016-12-24 12:19:12
【问题描述】:
组件“this”值的子组件以及如何获取父组件?
例如:
class AComponent extends Component{
static getThis(){
return this;
}
}
class MainComp extends Component{
componentDidMoud(){
console.log(AComponent.getThis());
}
}
这样,我怎么得到呢?
【问题讨论】:
标签:
reactjs
react-native
native
【解决方案1】:
您不应该从子组件中获取父组件。如果您需要做某事(即影响父组件状态),则将一个函数从父组件传递给子组件作为道具来执行。如果您需要阅读某些内容,则将相关数据从父级传递给子级作为读取它的道具。
【解决方案2】:
您可以将 props 向下传递给子组件,无论是供子组件使用的简单原始值,还是子组件可以用来更改父组件状态的函数。这是一个简单的例子。
ParentComponent.js
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
someState: true
};
this.someFunction = this.someFunction.bind(this);
}
someFunction() {
this.setState({
someState: false
});
}
render() {
return (
<ChildComponent aFunc={this.someFunction} aString="someValue"/>
);
}
}
ChildComponent.js
import React, { Component } from 'react';
class ChildComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={this.props.aString}>
<button onClick={this.props.aFunc}>
Some text
</button>
</div>
);
}
}