我是es6中的新手,此代码适用于React.createClass。我有一个共2个函数,我想传递另一个组件,我的问题是我很困惑它的'上下文,我的代码是这样的:
class AppOne extends React.Component {
constructor(props) {
super(props);
this.state = {
timers: [
{
title: 'Practice squat',
project: 'Gym Chores',
id: v4(),
elapsed: 5456099,
runningSince: Date.now()
},
{
title: 'Bake squash',
project: 'Kitchen Chores',
id: v4(),
elapsed: 1273998,
runningSince: null
},
],
};
this.func = this.func.bind(this);
this.stopTimer = this.stopTimer.bind(this); //<--"Uncaught TypeError: this.stopTimer is
// not a function"
}
func(timerId) {
this.stopTimer(timerId);
}
stopTimer(timerId) {
const now = Date.now();
this.setState({
timers: this.state.timers.map((timer) => {
if(timer.id === timerId) {
const lastElapsed = now - timer.runningSince;
return Object.assign({}, timer, {
elapsed: timer.elapsed + lastElapsed,
runningSince: null
});
} else {
return timer;
}
}),
});
}
render() {
return (
<AppTwo handleFuncFromAppOne = {this.func} timers={this.state.timers} />
);
}
}
class AppTwo extends React.Component {
handleFuncFromAppTwo() {
this.props.handleFuncFromAppOne(this.props.timers.id)
}
render() {
return(
<AppThree handleFuncFromAppThree={this.handleFuncFromAppTwo} />
);
}
}
class AppThree extends React.Component {
render() {
return (
<div
className='ui bottom attached red basic button'
onClick={this.props.handleFuncFromAppThree} // I want to invoke here
>
Stop
</div>
);
}
}
你看我已经把stopTimer绑定了它的&#39;这个在App One上它使用this.setState来改变状态,我的问题是我无法在App 3上调用它。我的错误是&#34; Uncaught TypeError:this.stopTimer不是函数&#34;。我似乎没有React.createClass的这个问题。帮助
答案 0 :(得分:1)
好的,你的问题是你没有传递你可以这样做的<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ahsan.islam.com.madpresentor"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="19" />
<uses-permission android:maxSdkVersion="22" android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:maxSdkVersion="22" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
所定义的类的引用:
// class Apptwo
handleFuncFromAppThree()
对于Appone类,你可以这么类似。
干杯:)