如果重複,我很抱歉。我將父函數傳遞給子,但是當我在子中使用此方法時,它給我這個錯誤 _this2.props.changeAppMode不是函數ReactJs調用父功能
我試過stackover流已經回答了問題,但無法解決它。我是個新手,所以可能我錯過了一些其他概念
以下是我的部件
父組件
class Users extends React.Component {
constructor(props) {
super(props);
this.state = {
currentMode: 'read',
userId: null
};
this.changeAppMode = this.changeAppMode.bind(this);
}
changeAppMode(newMode, userId) {
this.setState({currentMode: newMode});
if (userId !== undefined) {
this.setState({userId: userId});
}
}
render() {
var modeComponent =
<ReadUserComponent
changeAppMode={this.changeAppMode}/>;
switch (this.state.currentMode) {
case 'read':
break;
case 'readOne':
modeComponent = <ViewUser />;
break;
default:
break;
}
return modeComponent;
}
}
export default Users;
兒童的兒童
class ReadUserComponent extends React.Component {
constructor(props) {
super(props);
console.log(props);
};
componentDidMount() {
this.props.fetchUsers();
}
render(){
const users = this.props.users;
return (
<div className='overflow-hidden'>
<h1>Users List </h1>
<TopActionsComponent changeAppMode={this.props.changeAppMode} />
<UsersTable
users={users}
changeAppMode={this.props.changeAppMode} />
</div>
);
}
}
ReadUserComponent.propTypes = {
users: React.PropTypes.array.isRequired,
fetchUsers: React.PropTypes.func.isRequired
}
function mapStateToProps(state) {
return {
users: state.users
}
}
export default connect(mapStateToProps, { fetchUsers })(ReadUserComponent);
兒童[該組件調用父功能]
class TopActionsComponent extends React.Component {
render() {
return (
<div>
<a href='#'
onClick={() => this.props.changeAppMode('create')}
className='btn btn-primary margin-bottom-1em'> Create product
</a>
</div>
);
}
}
導出默認TopActionsComponent;
感謝您的期待。真的很感謝你的幫助
很抱歉,如果它是重複的,但我是那種一卡在它
你確定它不工作?我只是試圖在一個hello world類型的例子中重新創建它,並且它似乎在做它的工作。你期待的結果是什麼? – dubes
如果有幫助,可以在小提琴中找到一個簡單的例子:http://jsfiddle.net/09e93seL/1/ – dubes
是的,它的工作愚蠢的錯誤是在我的最後。謝謝大家。 * Mayank Shukla *告訴我要在每個階段打印道具,而且這樣做的訣竅。謝謝 –