【发布时间】:2017-05-11 18:17:28
【问题描述】:
我在 ReactJS 中有一个子类和一个父类。我希望我的孩子访问父母的状态,每毫秒更新一次。孩子也应该可以访问一些父母的方法。
家长:
interface StatesZeit{
datum : Date;
}
export default class StoppUhr extends React.Component<undefined, StatesZeit>{
uhrID : number;
constructor(){
super();
this.state = {
datum : new Date(0),
};
this.start = this.start.bind(this);
this.stopp = this.stopp.bind(this);
this.counter = this.counter.bind(this);
}
start() {
this.uhrID = setInterval(() => {
this.counter();
}, 0);
}
stopp() {
clearInterval(this.uhrID);
}
counter() {
this.setState({
datum : new Date()
});
}
render(){ // Returns the Child and passes the states as properties
return (
<ZeitManager stopp={this.stopp.bind(this)}
start={this.start.bind(this)}
counter={this.counter.bind(this)}
timeState={this.state.datum}/>
)
}
}
孩子
export interface PropsZM {
timeState : Date;
start(); // not sure if correct, should somehow reference functions of parent
stopp();// not sure if correct, should somehow reference functions of parent
counter();// not sure if correct, should somehow reference functions of parent
}
export class ZeitManager extends React.Component<PropsZM, undefined>{
private _millisec : number;
constructor(){
super();
this.startManager = this.startManager.bind(this);
this.stoppManager = this.stoppManager.bind(this);
}
startManager() {
this.props.start();
}
stoppManager() {
this.props.stopp();
this._millisec = this.props.timeState.getMilliseconds();
}
counterManager() {
this.props.counter;
}
get millisec(): number {
return this._millisec;
}
render(){
return <div>{this.props.start}</div>;
}
}
在另一个类中,我正在初始化一个子对象并在其上调用函数 startManager()。但随后我收到一条错误消息,提示 无法读取未定义的属性“开始”。我是 React 的新手,我认为我在这里定义孩子的属性时做错了。有谁知道我在这里做错了什么。谢谢
【问题讨论】:
-
你是如何“初始化一个子对象”的?
-
在另一个类的构造函数中。像构造函数 () { super(); this.zeitmanager = new Zeitmanager() } 然后我调用 zm 对象上的函数。像 zm.startManager()
标签: javascript reactjs typescript