我正在尝试将Onsen UI + React用于需要拆分器和导航的应用程序。 Page对象使用函数 renderToolbar ,其中定义了带方法的按钮以打开Splitter。
当我点击工具栏上的按钮时,这不是,但是当点击页面上的按钮时可以使用。为什么?
以下是完整代码:
import React from 'react';
import ReactDOM from 'react-dom';
import {
Toolbar, Page, Button, ToolbarButton, Icon, Input,
Splitter, SplitterSide, SplitterContent
} from 'react-onsenui';
import SecondPage from './SecondPage'
export default class MainPage extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
this.show = this.show.bind(this);
}
/**
* Show side menu
*/
show() {
this.setState({
isOpen: true
});
}
/**
* Hide side menu
*/
hide() {
this.setState({
isOpen: false
});
}
/**
* Push page to navigation stack
*/
pushPage() {
this.props.navigator.pushPage({component: SecondPage});
}
/**
* Render top toolbar (action bar)
*/
renderToolbar() {
return (
<Toolbar>
<div className="right">
<ToolbarButton onClick={this.show}><Icon icon='menu'/></ToolbarButton> <--- DON'T WORK!
</div>
</Toolbar>
);
}
render() {
return (
<Splitter>
<SplitterSide
side='left'
collapse={true}
isOpen={this.state.isOpen}
onClose={this.hide.bind(this)}
isSwipeable={true}>
<Page>
<div>Menu content</div>
</Page>
</SplitterSide>
<SplitterContent>
<Page renderToolbar={this.renderToolbar}>
<div>Main content</div>
<Button onClick={this.show}>Open</Button> <--- WORK!
</Page>
</SplitterContent>
</Splitter>
);
}
}
答案 0 :(得分:1)
经过多次变换,我意识到renderToolbar函数也需要有绑定,所以最后代码:
import React from 'react';
import ReactDOM from 'react-dom';
import {
Toolbar, Page, Button, ToolbarButton, Icon, Input,
Splitter, SplitterSide, SplitterContent
} from 'react-onsenui';
import SecondPage from './SecondPage'
export default class MainPage extends React.Component {
// const rightDirect = "right";
constructor(props) {
super(props);
this.state = {
isOpen: false
};
this.hide = this.hide.bind(this);
this.show = this.show.bind(this);
this.renderToolbar = this.renderToolbar.bind(this);
}
/**
* Show side menu
*/
show() {
this.setState({
isOpen: true
});
}
/**
* Hide side menu
*/
hide() {
this.setState({
isOpen: false
});
}
/**
* Push page to navigation stack
*/
pushPage() {
this.props.navigator.pushPage({component: SecondPage});
}
/**
*
*/
renderToolbar() {
console.log('Render TB', this);
return (
<Toolbar>
<div className="right">
<ToolbarButton onClick={this.show}><Icon icon='menu'/></ToolbarButton>
</div>
</Toolbar>
);
}
/**
*
* @returns {XML}
*/
render() {
return (
<Splitter>
<SplitterSide
side='left'
collapse={true}
isOpen={this.state.isOpen}
onClose={this.hide}
isSwipeable={true}>
<Page>
<div>Menu content</div>
</Page>
</SplitterSide>
<SplitterContent>
<Page renderToolbar={this.renderToolbar}>
<div>Main content</div>
</Page>
</SplitterContent>
</Splitter>
);
}
}